mirror of
https://github.com/midoks/mdserver-web.git
synced 2026-10-10 06:29:26 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c17314b634 | ||
|
|
92a4b28fbf | ||
|
|
733e4e81be | ||
|
|
8b99ae2515 | ||
|
|
2a72422402 | ||
|
|
145a259ef9 | ||
|
|
a34b7719c8 | ||
|
|
4d98455c35 | ||
|
|
c0c9def1fb | ||
|
|
02d8416466 | ||
|
|
d505740269 | ||
|
|
b1f6314df7 | ||
|
|
533653fe47 | ||
|
|
dff4551fb1 | ||
|
|
79723149a5 | ||
|
|
76da8a2ad5 | ||
|
|
645538e633 | ||
|
|
1a1b4e9f3a | ||
|
|
3afde01f93 | ||
|
|
a14db23971 | ||
|
|
316f06911b | ||
|
|
698d049314 | ||
|
|
d397d74f73 | ||
|
|
8a7447a4ee | ||
|
|
98414db41d | ||
|
|
7024185b59 | ||
|
|
495f16f2cf | ||
|
|
62444b7b6d | ||
|
|
50b11457f7 | ||
|
|
393cbc3974 | ||
|
|
ce3bfc2ebd | ||
|
|
b68e8f3650 | ||
|
|
59a2765b2f | ||
|
|
08c83edeb9 | ||
|
|
c114e9aca8 | ||
|
|
c5123268d0 | ||
|
|
54bbc3ff57 | ||
|
|
4658b991a9 | ||
|
|
52145e710b | ||
|
|
4acc48ded2 | ||
|
|
0d858f87ea | ||
|
|
f37f08a9f5 | ||
|
|
0b5fc1de55 | ||
|
|
8748777101 | ||
|
|
48ed0b8034 | ||
|
|
41c9f6b7b6 | ||
|
|
c47336b65f | ||
|
|
24d7204ccc | ||
|
|
8c00fb8859 | ||
|
|
c573b28f16 | ||
|
|
afad548cf9 | ||
|
|
2605849de2 | ||
|
|
77598fa8a7 | ||
|
|
b175ab735d | ||
|
|
54ed17ab8f | ||
|
|
cadf72ea69 | ||
|
|
dadb737f88 | ||
|
|
fef2acf683 | ||
|
|
4b6dbf8887 | ||
|
|
06c99e1cc1 | ||
|
|
afb3e920f8 | ||
|
|
2c346c9850 | ||
|
|
5b6c5be288 | ||
|
|
63bd806222 | ||
|
|
afe3848b71 | ||
|
|
cd361ec7ec | ||
|
|
eb399fe799 | ||
|
|
53e588b6fc | ||
|
|
612c104cca | ||
|
|
550ca7681a | ||
|
|
6a09706362 | ||
|
|
ca040e8986 | ||
|
|
6fcc980d5d | ||
|
|
b69adc9c7d | ||
|
|
67da343705 | ||
|
|
4b47e27a54 | ||
|
|
fba3ddc9a5 | ||
|
|
4769ce5be8 | ||
|
|
8e16cbf7f9 | ||
|
|
4225d4c040 | ||
|
|
b578f2fddc | ||
|
|
961c3423fd | ||
|
|
8040c8c67a | ||
|
|
5aca7d7c26 | ||
|
|
d9f99e6b7c | ||
|
|
3addb46708 | ||
|
|
e6b493237d | ||
|
|
7f42054a14 | ||
|
|
501af3da15 | ||
|
|
68727cbe91 | ||
|
|
c5207961f3 | ||
|
|
a04e05c7e8 | ||
|
|
5b8cca24aa | ||
|
|
cafe58f3fc | ||
|
|
d1e2781eb9 | ||
|
|
67c899fc84 | ||
|
|
7432548ff9 | ||
|
|
0c2c136097 | ||
|
|
2a7e21951b | ||
|
|
066185e404 | ||
|
|
bd431f1647 | ||
|
|
0a6e88d81d | ||
|
|
02c9988ef7 | ||
|
|
5ee7df4a46 | ||
|
|
5f382c0034 | ||
|
|
63d17c4d77 | ||
|
|
38722c1dc2 | ||
|
|
ea982b7261 | ||
|
|
73d9edced8 | ||
|
|
af03c004a3 | ||
|
|
ddd9e70ac2 | ||
|
|
8976a7a147 | ||
|
|
677ff8ec0c | ||
|
|
47d240e2b8 | ||
|
|
1f7bd76875 | ||
|
|
f04c70f022 | ||
|
|
5044cc5db9 | ||
|
|
4329b90ac4 | ||
|
|
f7873b6dcd | ||
|
|
a80d666786 | ||
|
|
0598704dce | ||
|
|
8f19a05755 | ||
|
|
f320d7cc69 | ||
|
|
1e97929a24 | ||
|
|
c66bbac97e | ||
|
|
1f7a0d2795 | ||
|
|
f05ce79e63 | ||
|
|
9f3d06191a | ||
|
|
2c6614a5ff | ||
|
|
905bad29cf | ||
|
|
9ba572a8ce | ||
|
|
85fc333d2c | ||
|
|
5bc27a4725 | ||
|
|
e5acf206f5 | ||
|
|
ae7afc2eb5 | ||
|
|
5c8527a5de | ||
|
|
274592229e | ||
|
|
60ddb13f8e | ||
|
|
f62af00fb7 | ||
|
|
9c6faefffd | ||
|
|
c9e27c2add | ||
|
|
97b1e8b9b3 | ||
|
|
18cdcd1436 | ||
|
|
7d783c64b6 | ||
|
|
0b65d69750 | ||
|
|
693dbb8cf1 | ||
|
|
117a99e729 | ||
|
|
45d4b8a5de | ||
|
|
a5791051b1 | ||
|
|
dc3f8f8e0b | ||
|
|
bf1d00c012 | ||
|
|
51cf851cea | ||
|
|
1e09408eb9 | ||
|
|
7659865caf | ||
|
|
ad1851d068 | ||
|
|
e174652afc | ||
|
|
a95e7aacd7 | ||
|
|
6aa638ef9a | ||
|
|
6f3d50bae5 | ||
|
|
301a5a95b8 | ||
|
|
d35b9dccc7 | ||
|
|
82680605ac | ||
|
|
5b148b3d1a | ||
|
|
714acd20e5 | ||
|
|
bf58cd8acc | ||
|
|
059053d27c | ||
|
|
185e73c26a | ||
|
|
569511d321 | ||
|
|
f88bf5059f | ||
|
|
05b63b8d2b | ||
|
|
3a197b273d | ||
|
|
f4fdbab41c | ||
|
|
f6b2940657 | ||
|
|
78b9ac5df0 | ||
|
|
3ea4272307 | ||
|
|
efc7cee9ad | ||
|
|
5c4805453d | ||
|
|
f6da241c85 | ||
|
|
d5b6eb2325 | ||
|
|
6ed2cddf71 | ||
|
|
9c31d76442 | ||
|
|
7aecbaf7df | ||
|
|
ee81a86d24 | ||
|
|
0a60d66732 | ||
|
|
c3e3cff472 | ||
|
|
194d46eb6a | ||
|
|
d66bc94edc | ||
|
|
fb4ffcd343 | ||
|
|
10c235e317 | ||
|
|
9c156928d8 | ||
|
|
771905d7f6 | ||
|
|
cd21b3f3e7 | ||
|
|
982026db24 | ||
|
|
f9b91d9989 | ||
|
|
f7b1159bd7 | ||
|
|
6aa49ddbcf | ||
|
|
866eddac1d | ||
|
|
af0cce4216 | ||
|
|
3951322d86 | ||
|
|
dfdd16b444 | ||
|
|
aa8fec2b7e | ||
|
|
2a8958ab84 | ||
|
|
f5125670ee | ||
|
|
2a8d4fb7a9 | ||
|
|
59f7fe2290 | ||
|
|
928db6e7e7 | ||
|
|
f3927bd6cf | ||
|
|
bb92727b56 | ||
|
|
21b80b1fce | ||
|
|
637da92834 | ||
|
|
f5859626a9 | ||
|
|
003449eb0a | ||
|
|
d27f926191 | ||
|
|
7483247d4d | ||
|
|
1ad841d3af | ||
|
|
27376d879c | ||
|
|
8b824447c1 | ||
|
|
a1d26dcd45 | ||
|
|
5e68c7bf0a | ||
|
|
481ae16713 | ||
|
|
2d2bd39f9e | ||
|
|
7246a878a5 | ||
|
|
542ee3cdb0 | ||
|
|
69503b223b | ||
|
|
78d8fa7ebf | ||
|
|
21e9d8f2d8 | ||
|
|
3c6adfbd44 | ||
|
|
c0e70abe6d | ||
|
|
f174e71228 | ||
|
|
7a9a811ea6 | ||
|
|
c7e3d9d9a3 | ||
|
|
161f7a1bc0 | ||
|
|
175cce0131 | ||
|
|
3735897ed2 | ||
|
|
30bfa5a630 | ||
|
|
594fdb4712 | ||
|
|
31a441ea02 | ||
|
|
06f7087fad | ||
|
|
e7b8f5afdc | ||
|
|
6b57addfa7 | ||
|
|
aea435fbaf | ||
|
|
9cd6656946 | ||
|
|
4f7df4b3c3 | ||
|
|
70d12b7b8d | ||
|
|
fe576c820a | ||
|
|
b48a53e0d7 | ||
|
|
4701839c33 | ||
|
|
916bc67c4d | ||
|
|
d7bba830cc | ||
|
|
7a28f8f57a | ||
|
|
41ee25aa7b | ||
|
|
c8aa91cfa3 | ||
|
|
98f27498b0 | ||
|
|
5444fe6455 | ||
|
|
9627c6e47b | ||
|
|
13597d6282 | ||
|
|
d09494e3aa | ||
|
|
d35439d286 | ||
|
|
ced48bab47 | ||
|
|
fe2df6cc8d | ||
|
|
8bdfe15101 | ||
|
|
42e9983b88 | ||
|
|
9b7c0b6f99 | ||
|
|
e421292c9e | ||
|
|
7b4d31779a | ||
|
|
f3b09056f3 | ||
|
|
a92ccea6c5 | ||
|
|
9da77a0a9b | ||
|
|
c233ecaaa7 | ||
|
|
5828b8b8cb | ||
|
|
a4a1a2c83c | ||
|
|
0e20bc182c | ||
|
|
99c0b0a81a | ||
|
|
3fa199fec4 | ||
|
|
194c36c6d8 | ||
|
|
2fb542f6b4 | ||
|
|
60af43ed31 | ||
|
|
9f02cf9744 | ||
|
|
846bd270df | ||
|
|
d910d4f462 | ||
|
|
13f5b1bf02 | ||
|
|
1fc3fd6247 | ||
|
|
36e3feb886 | ||
|
|
0ca34afacd | ||
|
|
ffb3288f3d | ||
|
|
e2f68a73ed | ||
|
|
92fa8da2f6 | ||
|
|
7c96ddd63e | ||
|
|
c4e7872179 | ||
|
|
d399cb2bb4 | ||
|
|
985cbc7eca | ||
|
|
27ed21a17d | ||
|
|
972165ba1a | ||
|
|
e76eb4d0e8 | ||
|
|
fd05c40dbb | ||
|
|
a1a7fa5c82 | ||
|
|
531de1407f | ||
|
|
ca455f13e8 | ||
|
|
ab5342b01f | ||
|
|
a5a57c5718 | ||
|
|
27999b21e6 | ||
|
|
d2c6caeef2 | ||
|
|
de30d8a41f | ||
|
|
d3abc8e7b2 | ||
|
|
b7aad65eb5 | ||
|
|
240b1dec27 | ||
|
|
4756e0f68b | ||
|
|
59f62b948a | ||
|
|
0ab0741031 | ||
|
|
2fd2f6e844 | ||
|
|
e534c6177a | ||
|
|
897c6322fc | ||
|
|
201e93f946 | ||
|
|
a78fd957ec | ||
|
|
3ce037b0a1 | ||
|
|
f3176340f8 | ||
|
|
7bfe096e8d | ||
|
|
066428fca8 | ||
|
|
a1313846c8 | ||
|
|
0433123abd | ||
|
|
72e99844dd | ||
|
|
3a7882e7fa | ||
|
|
bec2a9a12c | ||
|
|
8f02363782 | ||
|
|
939c847f3e | ||
|
|
a623039db7 | ||
|
|
b7f49a1839 | ||
|
|
f1f60870f6 | ||
|
|
3b04739fd4 | ||
|
|
fdf1e0b0be | ||
|
|
d3385f526f | ||
|
|
20f9095b93 | ||
|
|
757cf483a2 | ||
|
|
1712cfd024 | ||
|
|
2b524cbe75 | ||
|
|
607d384000 | ||
|
|
14cdc7b82e | ||
|
|
c3219bcba2 | ||
|
|
a12c4dd78e | ||
|
|
39c6f19592 | ||
|
|
f18c05a097 | ||
|
|
80f296ea19 | ||
|
|
b3e9283a58 | ||
|
|
2e140a3ae1 | ||
|
|
4d733c8886 | ||
|
|
62a7320baf | ||
|
|
3dc7c2f5c1 | ||
|
|
fe62bbee06 | ||
|
|
f7c0cd82a0 | ||
|
|
13a2014558 | ||
|
|
5981f94376 | ||
|
|
005e0f1513 | ||
|
|
63a0f0fbdc | ||
|
|
edc0be11a1 | ||
|
|
908b6e67c6 | ||
|
|
dfe46332db | ||
|
|
fcdf2e18b2 | ||
|
|
3c8f9bcf96 | ||
|
|
ebadd6d80d | ||
|
|
6062699074 | ||
|
|
df9d57ba70 | ||
|
|
ffca953539 | ||
|
|
bd4946124f | ||
|
|
8e18c63cee | ||
|
|
d201ca2574 | ||
|
|
b644f91090 | ||
|
|
931f51cf59 | ||
|
|
0909a11fd9 | ||
|
|
2ba2833699 | ||
|
|
20389263fb | ||
|
|
86141ccf3a | ||
|
|
b2fdf84ca0 | ||
|
|
8fbc456e1a | ||
|
|
4e43382496 | ||
|
|
0326d4f112 | ||
|
|
a87c13c5e0 | ||
|
|
5f3720c855 | ||
|
|
f548e020c4 | ||
|
|
7f21781c0b | ||
|
|
680b0f09f2 | ||
|
|
482943a63c | ||
|
|
2871aee18e | ||
|
|
ff46d9b36e | ||
|
|
fd5fcba543 | ||
|
|
fe04e02e88 | ||
|
|
93554332a7 | ||
|
|
b541c7e1b7 | ||
|
|
1dec1a286a | ||
|
|
b17510104d | ||
|
|
c2c8ea0ce6 | ||
|
|
acbdb013ae | ||
|
|
b025f21765 | ||
|
|
1afc8a69e5 | ||
|
|
743fc9e8d3 | ||
|
|
8d692d2b3b | ||
|
|
a0b362e691 | ||
|
|
98e1c2ae8f | ||
|
|
c0e5915285 | ||
|
|
667a0fd0fd | ||
|
|
8ed5f283b0 | ||
|
|
643c370d30 | ||
|
|
4601303065 | ||
|
|
14940d6734 | ||
|
|
fdc2b0f5c4 | ||
|
|
cf0b233f63 | ||
|
|
b3a7ef2206 | ||
|
|
9a3ca3e833 | ||
|
|
9afff8df3f | ||
|
|
ccd0b06223 | ||
|
|
7b495fe9bf | ||
|
|
2c3fb75e8f | ||
|
|
53b606602f | ||
|
|
ecef0cf994 | ||
|
|
3691d41b23 | ||
|
|
1f66457a3e | ||
|
|
8e05beccfd | ||
|
|
35424eae1f | ||
|
|
ed6df6d527 | ||
|
|
4366c4afde | ||
|
|
4bb059f62f | ||
|
|
aa8f618d9c | ||
|
|
dfd753e4c1 | ||
|
|
e38daf3c89 | ||
|
|
535838fc5e | ||
|
|
797853bd61 | ||
|
|
0de3aff045 | ||
|
|
0b7b48ab23 | ||
|
|
5ff0a0bfbc | ||
|
|
9131f44d67 | ||
|
|
6b86bb9d2b | ||
|
|
dc06d6beda | ||
|
|
2c8ea2498e | ||
|
|
6b01173b61 | ||
|
|
883c554850 | ||
|
|
d267da351c | ||
|
|
13a39f4d6a | ||
|
|
cff1d5ee89 | ||
|
|
bf5274c313 | ||
|
|
5623e3efac | ||
|
|
b93bb6c64c | ||
|
|
c9962f169e | ||
|
|
080f343ee2 | ||
|
|
5aeaf13f16 | ||
|
|
528094cfa7 | ||
|
|
ed3e3336b2 | ||
|
|
a75a49c2ae | ||
|
|
1204e72f41 | ||
|
|
13ca5544a5 | ||
|
|
e53fe26d52 | ||
|
|
13772399f6 | ||
|
|
98f11e2662 | ||
|
|
f0b0302f75 | ||
|
|
5b9b466cb9 | ||
|
|
5588a11ea5 | ||
|
|
da05a4ef19 | ||
|
|
34cf899529 | ||
|
|
0d7d67b012 | ||
|
|
5b778bfc0d | ||
|
|
6ce414cecf | ||
|
|
c8160b63e7 | ||
|
|
68d957fd6e | ||
|
|
f09c438500 | ||
|
|
9bc9944a3e | ||
|
|
9e4c2b13d5 | ||
|
|
cd7143047f | ||
|
|
d608ac4d94 | ||
|
|
9fedf9d10d | ||
|
|
9936191da2 | ||
|
|
538eba3acf | ||
|
|
e39ee9a6f7 | ||
|
|
e1820ad5b3 | ||
|
|
22133f1a6c | ||
|
|
0041cbdff3 | ||
|
|
889da3c769 | ||
|
|
d086eb9c61 | ||
|
|
832fa9cd1a | ||
|
|
8c19fb9629 | ||
|
|
a2e4dd6753 | ||
|
|
22ba7dda55 | ||
|
|
2ffa36eecb | ||
|
|
fe5843b35d | ||
|
|
e95acbe947 | ||
|
|
aed8319dd3 | ||
|
|
babe1b885e | ||
|
|
0612f52402 | ||
|
|
db67cea737 | ||
|
|
52cf675843 | ||
|
|
3421bf6ab5 | ||
|
|
2f39bd600b | ||
|
|
acd5ec69e8 | ||
|
|
09878728af | ||
|
|
af82e9f129 | ||
|
|
c74630e738 | ||
|
|
e4e0697b4b | ||
|
|
11b5ac658b | ||
|
|
1306731164 | ||
|
|
bb6c933aee | ||
|
|
d6a93ef1e6 | ||
|
|
6610da402a | ||
|
|
3ace9cf51e | ||
|
|
49c7ec6073 | ||
|
|
8cf526667e | ||
|
|
6c42876411 | ||
|
|
79471e3806 | ||
|
|
cad06425fc | ||
|
|
6f1e11e474 | ||
|
|
59d13e50ce | ||
|
|
5da0746240 | ||
|
|
192ea8b029 | ||
|
|
bfc20b3e42 | ||
|
|
56bee5c752 | ||
|
|
312df5de1f | ||
|
|
4d3640286c | ||
|
|
20930806b6 | ||
|
|
71360b61da | ||
|
|
411645c9e2 | ||
|
|
3de4e1bfff | ||
|
|
34285f6051 | ||
|
|
84f0cda89b | ||
|
|
04012085ce | ||
|
|
9ad00f3ce7 | ||
|
|
609a4ed351 | ||
|
|
5ca74fd312 | ||
|
|
3b1bb06c68 | ||
|
|
b6b7de42d6 | ||
|
|
3aa3b532ac | ||
|
|
290c740ab1 | ||
|
|
23fd4ca1de | ||
|
|
c128a799b2 | ||
|
|
401c103b76 | ||
|
|
6fb88eb428 | ||
|
|
956f20d295 | ||
|
|
03f8578a37 |
@@ -0,0 +1,16 @@
|
||||
name: sync2gitee
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
repo-sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Mirror the Github organization repos to Gitee.
|
||||
uses: Yikun/hub-mirror-action@master
|
||||
with:
|
||||
src: 'github/midoks'
|
||||
dst: 'gitee/midoks'
|
||||
dst_key: ${{ secrets.GITEE_PRIVATE_KEY }}
|
||||
dst_token: ${{ secrets.GITEE_TOKEN }}
|
||||
static_list: "mdserver-web"
|
||||
force_update: true
|
||||
+2
-3
@@ -161,11 +161,8 @@ plugins/own_*
|
||||
plugins/my_*
|
||||
plugins/l2tp
|
||||
plugins/openlitespeed
|
||||
plugins/system_safe
|
||||
plugins/tamper_proof
|
||||
plugins/tamper_proof_*
|
||||
plugins/cryptocurrency_trade
|
||||
plugins/op_load_balance
|
||||
plugins/gdrive
|
||||
plugins/mtproxy
|
||||
plugins/zimg
|
||||
@@ -180,3 +177,5 @@ debug.out
|
||||
|
||||
|
||||
|
||||
mdioks.session-journal
|
||||
*.session
|
||||
|
||||
@@ -79,7 +79,7 @@ PHP[72-82]支持phpMyAdmin[5.2.0]
|
||||
|
||||
# 特别赞助
|
||||
|
||||
- [找资源 - 阿里云盘资源搜索引擎](https://zhaoziyuan.la/)
|
||||
- [找资源 - 阿里云盘资源搜索引擎](https://zhaoziyuan.pw/)
|
||||
|
||||
# AD - VPS推荐 - 🙏
|
||||
|
||||
@@ -99,30 +99,34 @@ docker run -itd --name mw-server --privileged=true -p 7200:7200 -p 80:80 -p 443:
|
||||
```
|
||||
|
||||
|
||||
### 版本更新 0.13.3
|
||||
### 版本更新 0.15.2
|
||||
|
||||
* tgbot插件[增加扩展功能]。
|
||||
* ssl功能优化。
|
||||
* 网站统计-计划任务归档优化。
|
||||
* OpenResty升级到1.21.4.2
|
||||
* 计划任务自动脚本运行时间
|
||||
* rsyncd添加优化
|
||||
* 使用mariadb二进制导入备份文件
|
||||
* docker插件-镜像导入导出功能
|
||||
* 网站设置反向代理升级功能
|
||||
* 优化初始化安装SSH端口识别
|
||||
|
||||
### JSDelivr安装地址
|
||||
|
||||
- 初始安装
|
||||
|
||||
```
|
||||
curl -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
- 直接更新
|
||||
|
||||
```
|
||||
curl -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/update.sh | bash
|
||||
curl --insecure -fsSL https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/update.sh | bash
|
||||
```
|
||||
|
||||
- 卸载脚本
|
||||
|
||||
```
|
||||
wget -O uninstall.sh https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/uninstall.sh && bash uninstall.sh
|
||||
wget --no-check-certificate -O uninstall.sh https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scripts/uninstall.sh && bash uninstall.sh
|
||||
```
|
||||
|
||||
### 备用地址
|
||||
@@ -130,20 +134,20 @@ wget -O uninstall.sh https://cdn.jsdelivr.net/gh/midoks/mdserver-web@latest/scri
|
||||
- 初始安装
|
||||
|
||||
```
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://gitee.com/midoks/mdserver-web/raw/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/install.sh | bash
|
||||
curl --insecure -fsSL https://code.midoks.me/midoks/mdserver-web/raw/branch/master/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
- 直接更新
|
||||
|
||||
```
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/update.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/update.sh | bash
|
||||
```
|
||||
|
||||
- 卸载脚本
|
||||
|
||||
```
|
||||
wget -O uninstall.sh https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/uninstall.sh && bash uninstall.sh
|
||||
wget --no-check-certificate -O uninstall.sh https://raw.githubusercontent.com/midoks/mdserver-web/master/scripts/uninstall.sh && bash uninstall.sh
|
||||
```
|
||||
|
||||
|
||||
@@ -152,22 +156,22 @@ wget -O uninstall.sh https://raw.githubusercontent.com/midoks/mdserver-web/maste
|
||||
- 需已经安装mdserver-web
|
||||
|
||||
```
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/quick/app.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/quick/app.sh | bash
|
||||
```
|
||||
|
||||
|
||||
### DEV使用
|
||||
|
||||
```
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/install_dev.sh | bash
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/update_dev.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/install_dev.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/update_dev.sh | bash
|
||||
|
||||
wget -O uninstall.sh https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/uninstall.sh && bash uninstall.sh
|
||||
wget --no-check-certificate -O uninstall.sh https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/uninstall.sh && bash uninstall.sh
|
||||
|
||||
curl -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/quick/debug.sh | bash
|
||||
curl --insecure -fsSL https://raw.githubusercontent.com/midoks/mdserver-web/dev/scripts/quick/debug.sh | bash
|
||||
|
||||
curl -fsSL https://gitee.com/midoks/mdserver-web/raw/dev/scripts/install_dev.sh | bash
|
||||
curl -fsSL https://gitee.com/midoks/mdserver-web/raw/dev/scripts/update_dev.sh | bash
|
||||
curl --insecure -fsSL https://code.midoks.me/midoks/mdserver-web/raw/branch/dev/scripts/install_dev.sh | bash
|
||||
curl --insecure -fsSL https://code.midoks.me/midoks/mdserver-web/raw/branch/dev/scripts/update_dev.sh | bash
|
||||
```
|
||||
|
||||
### 捐赠地址 USDT(TRC20)
|
||||
|
||||
@@ -28,6 +28,7 @@ from route import app, socketio
|
||||
from gevent.pywsgi import WSGIServer
|
||||
from geventwebsocket.handler import WebSocketHandler
|
||||
|
||||
|
||||
from gevent import monkey
|
||||
monkey.patch_all()
|
||||
|
||||
|
||||
@@ -930,7 +930,8 @@ fi
|
||||
index).encode()
|
||||
)
|
||||
X509Req.set_pubkey(pk)
|
||||
X509Req.set_version(2)
|
||||
# X509Req.set_version(2)
|
||||
X509Req.set_version(0)
|
||||
X509Req.sign(pk, self.__digest)
|
||||
return OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, X509Req)
|
||||
|
||||
@@ -1006,7 +1007,7 @@ fi
|
||||
try:
|
||||
result = {}
|
||||
x509 = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.crypto.FILETYPE_PEM, public.readFile(pem_file))
|
||||
OpenSSL.crypto.FILETYPE_PEM, mw.readFile(pem_file))
|
||||
# 取产品名称
|
||||
issuer = x509.get_issuer()
|
||||
result['issuer'] = ''
|
||||
@@ -1280,16 +1281,16 @@ fullchain.pem 粘贴到证书输入框
|
||||
# 获取当前正在使用此证书的网站目录
|
||||
def getSslUsedSite(self, save_path):
|
||||
pkey_file = '{}/privkey.pem'.format(save_path)
|
||||
pkey = public.readFile(pkey_file)
|
||||
pkey = mw.readFile(pkey_file)
|
||||
if not pkey:
|
||||
return False
|
||||
cert_paths = 'vhost/cert'
|
||||
import panelSite
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
args.siteName = ''
|
||||
for c_name in os.listdir(cert_paths):
|
||||
skey_file = '{}/{}/privkey.pem'.format(cert_paths, c_name)
|
||||
skey = public.readFile(skey_file)
|
||||
skey = mw.readFile(skey_file)
|
||||
if not skey:
|
||||
continue
|
||||
if skey == pkey:
|
||||
@@ -1297,7 +1298,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
run_path = panelSite.panelSite().GetRunPath(args)
|
||||
if not run_path:
|
||||
continue
|
||||
sitePath = public.M('sites').where(
|
||||
sitePath = mw.M('sites').where(
|
||||
'name=?', c_name).getField('path')
|
||||
if not sitePath:
|
||||
continue
|
||||
@@ -1315,7 +1316,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
self.__config['orders'] = {}
|
||||
import panelSite
|
||||
siteObj = panelSite.panelSite()
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
for siteName in os.listdir(cert_path):
|
||||
try:
|
||||
cert_file = '{}/{}/fullchain.pem'.format(cert_path, siteName)
|
||||
|
||||
@@ -840,7 +840,8 @@ class cert_request:
|
||||
index).encode()
|
||||
)
|
||||
X509Req.set_pubkey(pk)
|
||||
X509Req.set_version(2)
|
||||
# X509Req.set_version(2)
|
||||
X509Req.set_version(0)
|
||||
X509Req.sign(pk, self.__digest)
|
||||
return OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, X509Req)
|
||||
|
||||
@@ -916,7 +917,7 @@ class cert_request:
|
||||
try:
|
||||
result = {}
|
||||
x509 = OpenSSL.crypto.load_certificate(
|
||||
OpenSSL.crypto.FILETYPE_PEM, public.readFile(pem_file))
|
||||
OpenSSL.crypto.FILETYPE_PEM, mw.readFile(pem_file))
|
||||
# 取产品名称
|
||||
issuer = x509.get_issuer()
|
||||
result['issuer'] = ''
|
||||
@@ -1186,16 +1187,16 @@ fullchain.pem 粘贴到证书输入框
|
||||
# 获取当前正在使用此证书的网站目录
|
||||
def getSslUsedSite(self, save_path):
|
||||
pkey_file = '{}/privkey.pem'.format(save_path)
|
||||
pkey = public.readFile(pkey_file)
|
||||
pkey = mw.readFile(pkey_file)
|
||||
if not pkey:
|
||||
return False
|
||||
cert_paths = 'vhost/cert'
|
||||
import panelSite
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
args.siteName = ''
|
||||
for c_name in os.listdir(cert_paths):
|
||||
skey_file = '{}/{}/privkey.pem'.format(cert_paths, c_name)
|
||||
skey = public.readFile(skey_file)
|
||||
skey = mw.readFile(skey_file)
|
||||
if not skey:
|
||||
continue
|
||||
if skey == pkey:
|
||||
@@ -1203,7 +1204,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
run_path = panelSite.panelSite().GetRunPath(args)
|
||||
if not run_path:
|
||||
continue
|
||||
sitePath = public.M('sites').where(
|
||||
sitePath = mw.M('sites').where(
|
||||
'name=?', c_name).getField('path')
|
||||
if not sitePath:
|
||||
continue
|
||||
@@ -1221,7 +1222,7 @@ fullchain.pem 粘贴到证书输入框
|
||||
self.__config['orders'] = {}
|
||||
import panelSite
|
||||
siteObj = panelSite.panelSite()
|
||||
args = public.dict_obj()
|
||||
args = mw.dict_obj()
|
||||
for siteName in os.listdir(cert_path):
|
||||
try:
|
||||
cert_file = '{}/{}/fullchain.pem'.format(cert_path, siteName)
|
||||
|
||||
@@ -33,6 +33,7 @@ from flask import redirect
|
||||
|
||||
def init():
|
||||
initDB()
|
||||
initDBSshPort()
|
||||
initUserInfo()
|
||||
initInitD()
|
||||
initInitTask()
|
||||
@@ -62,6 +63,17 @@ def initDB():
|
||||
print(str(ex))
|
||||
|
||||
|
||||
def initDBSshPort():
|
||||
# SSH端口必须放开
|
||||
import firewall_api
|
||||
cmd_data = mw.execShell(
|
||||
"cat /etc/ssh/sshd_config | grep '^Port \d*' | tail -1")
|
||||
ssh_port = cmd_data[0].replace("Port ", '').strip()
|
||||
if ssh_port == '':
|
||||
ssh_port = '22'
|
||||
firewall_api.firewall_api().addAcceptPortArgs(ssh_port, 'SSH远程管理服务', 'port')
|
||||
|
||||
|
||||
def doContentReplace(src, dst):
|
||||
content = mw.readFile(src)
|
||||
content = content.replace("{$SERVER_PATH}", mw.getRunDir())
|
||||
|
||||
@@ -27,7 +27,7 @@ from flask import request
|
||||
|
||||
class config_api:
|
||||
|
||||
__version = '0.13.3'
|
||||
__version = '0.15.3'
|
||||
__api_addr = 'data/api.json'
|
||||
|
||||
def __init__(self):
|
||||
@@ -788,6 +788,13 @@ class config_api:
|
||||
return mw.returnData(True, '验证成功')
|
||||
return mw.returnData(False, '验证失败')
|
||||
|
||||
if tag == 'email':
|
||||
t = json.loads(tag_data)
|
||||
test_bool = mw.emailNotifyTest(t)
|
||||
if test_bool:
|
||||
return mw.returnData(True, '验证成功')
|
||||
return mw.returnData(False, '验证失败')
|
||||
|
||||
return mw.returnData(False, '暂时未支持该验证')
|
||||
|
||||
def setNotifyEnableApi(self):
|
||||
|
||||
@@ -508,6 +508,22 @@ class crontab_api:
|
||||
else:
|
||||
head = "#!/bin/bash\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n"
|
||||
|
||||
start_head = '''
|
||||
SCRIPT_RUN_TIME="0s"
|
||||
MW_ToSeconds()
|
||||
{
|
||||
SEC=$1
|
||||
if [ $SEC -lt 60 ]; then
|
||||
SCRIPT_RUN_TIME="${SEC}s"
|
||||
elif [ $SEC -ge 60 ] && [ $SEC -lt 3600 ];then
|
||||
SCRIPT_RUN_TIME="$(( SEC / 60 ))m$(( SEC % 60 ))s"
|
||||
elif [ $SEC -ge 3600 ]; then
|
||||
SCRIPT_RUN_TIME="$(( SEC / 3600 ))h$(( (SEC % 3600) / 60 ))m$(( (SEC % 3600) % 60 ))s"
|
||||
fi
|
||||
}
|
||||
START_MW_SHELL_TIME=`date +%s`
|
||||
'''
|
||||
|
||||
source_bin_activate = '''
|
||||
export LANG=en_US.UTF-8
|
||||
MW_PATH=%s/bin/activate
|
||||
@@ -515,7 +531,7 @@ if [ -f $MW_PATH ];then
|
||||
source $MW_PATH
|
||||
fi''' % (mw.getRunDir(),)
|
||||
|
||||
head = head + source_bin_activate + "\n"
|
||||
head = head + start_head + source_bin_activate + "\n"
|
||||
log = '.log'
|
||||
|
||||
script_dir = mw.getRunDir() + "/scripts"
|
||||
@@ -557,7 +573,10 @@ fi''' % (mw.getRunDir(),)
|
||||
shell += '''
|
||||
echo "----------------------------------------------------------------------------"
|
||||
endDate=`date +"%Y-%m-%d %H:%M:%S"`
|
||||
echo "★[$endDate] Successful"
|
||||
END_MW_SHELL_TIME=`date +"%s"`
|
||||
((SHELL_COS_TIME=($END_MW_SHELL_TIME-$START_MW_SHELL_TIME)))
|
||||
MW_ToSeconds $SHELL_COS_TIME
|
||||
echo "★[$endDate] Successful | Script Run [$SCRIPT_RUN_TIME] "
|
||||
echo "----------------------------------------------------------------------------"
|
||||
'''
|
||||
cronPath = mw.getServerDir() + '/cron'
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ class Sql():
|
||||
self.__DB_TABLE = table
|
||||
return self
|
||||
|
||||
def where(self, where, param):
|
||||
def where(self, where, param=()):
|
||||
# WHERE条件
|
||||
if where:
|
||||
self.__OPT_WHERE = " WHERE " + where
|
||||
|
||||
+174
-4
@@ -23,11 +23,13 @@ import shlex
|
||||
import datetime
|
||||
import subprocess
|
||||
import glob
|
||||
|
||||
import base64
|
||||
import re
|
||||
import db
|
||||
|
||||
from random import Random
|
||||
|
||||
import db
|
||||
|
||||
|
||||
def execShell(cmdstring, cwd=None, timeout=None, shell=True):
|
||||
|
||||
@@ -776,6 +778,133 @@ def deDoubleCrypt(key, strings):
|
||||
return strings
|
||||
|
||||
|
||||
def aesEncrypt(data, key='ABCDEFGHIJKLMNOP', vi='0102030405060708'):
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
if not isinstance(data, bytes):
|
||||
data = data.encode()
|
||||
|
||||
# AES_CBC_KEY = os.urandom(32)
|
||||
# AES_CBC_IV = os.urandom(16)
|
||||
|
||||
AES_CBC_KEY = key.encode()
|
||||
AES_CBC_IV = vi.encode()
|
||||
|
||||
# print("AES_CBC_KEY:", AES_CBC_KEY)
|
||||
# print("AES_CBC_IV:", AES_CBC_IV)
|
||||
|
||||
padder = padding.PKCS7(algorithms.AES.block_size).padder()
|
||||
padded_data = padder.update(data) + padder.finalize()
|
||||
|
||||
cipher = Cipher(algorithms.AES(AES_CBC_KEY),
|
||||
modes.CBC(AES_CBC_IV),
|
||||
backend=default_backend())
|
||||
encryptor = cipher.encryptor()
|
||||
|
||||
edata = encryptor.update(padded_data)
|
||||
|
||||
# print(edata)
|
||||
# print(str(edata))
|
||||
# print(edata.decode())
|
||||
return edata
|
||||
|
||||
|
||||
def aesDecrypt(data, key='ABCDEFGHIJKLMNOP', vi='0102030405060708'):
|
||||
# aes加密
|
||||
# @param data 被解密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
if not isinstance(data, bytes):
|
||||
data = data.encode()
|
||||
|
||||
AES_CBC_KEY = key.encode()
|
||||
AES_CBC_IV = vi.encode()
|
||||
|
||||
cipher = Cipher(algorithms.AES(AES_CBC_KEY),
|
||||
modes.CBC(AES_CBC_IV),
|
||||
backend=default_backend())
|
||||
decryptor = cipher.decryptor()
|
||||
|
||||
ddata = decryptor.update(data)
|
||||
|
||||
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
|
||||
data = unpadder.update(ddata)
|
||||
|
||||
try:
|
||||
uppadded_data = data + unpadder.finalize()
|
||||
except ValueError:
|
||||
raise Exception('无效的加密信息!')
|
||||
|
||||
return uppadded_data
|
||||
|
||||
|
||||
def aesEncrypt_Crypto(data, key, vi):
|
||||
# 该方法保留,暂时不使用
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
cryptor = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
|
||||
# 判断是否含有中文
|
||||
zhmodel = re.compile(u'[\u4e00-\u9fff]')
|
||||
match = zhmodel.search(data)
|
||||
if match == None:
|
||||
# 无中文时
|
||||
add = 16 - len(data) % 16
|
||||
pad = lambda s: s + add * chr(add)
|
||||
data = pad(data)
|
||||
enctext = cryptor.encrypt(data.encode('utf8'))
|
||||
else:
|
||||
# 含有中文时
|
||||
data = data.encode()
|
||||
add = 16 - len(data) % 16
|
||||
data = data + add * (chr(add)).encode()
|
||||
enctext = cryptor.encrypt(data)
|
||||
encodestrs = base64.b64encode(enctext).decode('utf8')
|
||||
return encodestrs
|
||||
|
||||
|
||||
def aesDecrypt_Crypto(data, key, vi):
|
||||
# 该方法保留,暂时不使用
|
||||
# aes加密
|
||||
# @param data 被加密的数据
|
||||
# @param key 加解密密匙 16位
|
||||
# @param vi 16位
|
||||
|
||||
from crypto.Cipher import AES
|
||||
data = data.encode('utf8')
|
||||
encodebytes = base64.urlsafe_b64decode(data)
|
||||
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
|
||||
text_decrypted = cipher.decrypt(encodebytes)
|
||||
# 判断是否含有中文
|
||||
zhmodel = re.compile(u'[\u4e00-\u9fff]')
|
||||
match = zhmodel.search(text_decrypted)
|
||||
if match == False:
|
||||
# 无中文时补位
|
||||
unpad = lambda s: s[0:-s[-1]]
|
||||
text_decrypted = unpad(text_decrypted)
|
||||
text_decrypted = text_decrypted.decode('utf8').rstrip() # 去掉补位的右侧空格
|
||||
return text_decrypted
|
||||
|
||||
|
||||
def buildSoftLink(src, dst, force=False):
|
||||
'''
|
||||
建立软连接
|
||||
@@ -1086,6 +1215,12 @@ def formatDate(format="%Y-%m-%d %H:%M:%S", times=None):
|
||||
return time.strftime(format, time_local)
|
||||
|
||||
|
||||
def strfToTime(sdate):
|
||||
# 转换时间
|
||||
import time
|
||||
return time.strftime('%Y-%m-%d', time.strptime(sdate, '%b %d %H:%M:%S %Y %Z'))
|
||||
|
||||
|
||||
def checkIp(ip):
|
||||
# 检查是否为IPv4地址
|
||||
import re
|
||||
@@ -1276,7 +1411,7 @@ def makeConf():
|
||||
file = getRunDir() + '/data/json/config.json'
|
||||
if not os.path.exists(file):
|
||||
c = {}
|
||||
c['title'] = '金蝉面板'
|
||||
c['title'] = '金灵面板'
|
||||
c['home'] = 'http://github/midoks/mdserver-web'
|
||||
c['recycle_bin'] = True
|
||||
c['template'] = 'default'
|
||||
@@ -1697,7 +1832,7 @@ def getNotifyData(is_parse=False):
|
||||
data = json.loads(notify_data)
|
||||
|
||||
if is_parse:
|
||||
tag_list = ['tgbot']
|
||||
tag_list = ['tgbot', 'email']
|
||||
for t in tag_list:
|
||||
if t in data and 'cfg' in data[t]:
|
||||
data[t]['data'] = json.loads(deDoubleCrypt(t, data[t]['cfg']))
|
||||
@@ -1759,6 +1894,34 @@ def tgbotNotifyTest(app_token, chat_id):
|
||||
return tgbotNotifyHttpPost(app_token, chat_id, msg)
|
||||
|
||||
|
||||
def emailNotifyMessage(data):
|
||||
'''
|
||||
邮件通知
|
||||
'''
|
||||
sys.path.append(os.getcwd() + "/class/plugin")
|
||||
import memail
|
||||
try:
|
||||
if data['smtp_ssl'] == 'ssl':
|
||||
memail.sendSSL(data['smtp_host'], data['smtp_port'],
|
||||
data['username'], data['password'],
|
||||
data['to_mail_addr'], data['subject'], data['content'])
|
||||
else:
|
||||
memail.send(data['smtp_host'], data['smtp_port'],
|
||||
data['username'], data['password'],
|
||||
data['to_mail_addr'], data['subject'], data['content'])
|
||||
return True
|
||||
except Exception as e:
|
||||
print(getTracebackInfo())
|
||||
return False
|
||||
|
||||
|
||||
def emailNotifyTest(data):
|
||||
# print(data)
|
||||
data['subject'] = 'MW通知测试'
|
||||
data['content'] = data['mail_test']
|
||||
return emailNotifyMessage(data)
|
||||
|
||||
|
||||
def notifyMessageTry(msg, stype='common', trigger_time=300, is_write_log=True):
|
||||
|
||||
lock_file = getPanelTmp() + '/notify_lock.json'
|
||||
@@ -1796,6 +1959,13 @@ def notifyMessageTry(msg, stype='common', trigger_time=300, is_write_log=True):
|
||||
else:
|
||||
do_notify = tgbotNotifyMessage(
|
||||
t['app_token'], t['chat_id'], msg)
|
||||
|
||||
if 'email' in data and 'enable' in data['email']:
|
||||
if data['email']['enable']:
|
||||
t = data['email']['data']
|
||||
t['subject'] = 'MW通知'
|
||||
t['content'] = msg
|
||||
do_notify = emailNotifyMessage(t)
|
||||
return do_notify
|
||||
|
||||
|
||||
|
||||
+27
-10
@@ -71,8 +71,9 @@ class plugins_api:
|
||||
if not mw.isNumber(sType):
|
||||
sType = 0
|
||||
|
||||
# print sPage
|
||||
data = self.getPluginList(sType, int(sPage))
|
||||
# print(sPage, sType)
|
||||
search = request.args.get('search', '').lower()
|
||||
data = self.getPluginList(sType, search, int(sPage))
|
||||
return mw.getJson(data)
|
||||
|
||||
def menuGetAbsPath(self, tag, path):
|
||||
@@ -138,7 +139,7 @@ class plugins_api:
|
||||
def initApi(self):
|
||||
|
||||
plugin_names = {
|
||||
'openresty': '1.21.4.1',
|
||||
'openresty': '1.21.4.2',
|
||||
'php': '56',
|
||||
'swap': '1.1',
|
||||
'mysql': '5.7',
|
||||
@@ -781,7 +782,18 @@ class plugins_api:
|
||||
print(e)
|
||||
return plugins_info
|
||||
|
||||
def getAllListPage(self, sType='0', page=1, pageSize=10):
|
||||
def searchKey(self, info, kw):
|
||||
try:
|
||||
if info['title'].lower().find(kw) > -1:
|
||||
return True
|
||||
if info['ps'].lower().find(kw) > -1:
|
||||
return True
|
||||
if info['name'].lower().find(kw) > -1:
|
||||
return True
|
||||
except Exception as e:
|
||||
return False
|
||||
|
||||
def getAllListPage(self, sType='0', kw='', page=1, pageSize=10):
|
||||
plugins_info = []
|
||||
for dirinfo in os.listdir(self.__plugin_dir):
|
||||
if dirinfo[0:1] == '.':
|
||||
@@ -792,11 +804,13 @@ class plugins_api:
|
||||
if os.path.exists(json_file):
|
||||
try:
|
||||
data = json.loads(mw.readFile(json_file))
|
||||
# 判断是否搜索
|
||||
if kw != '' and not self.searchKey(data, kw):
|
||||
continue
|
||||
tmp_data = self.makeList(data, sType)
|
||||
for index in range(len(tmp_data)):
|
||||
plugins_info.append(tmp_data[index])
|
||||
except Exception as e:
|
||||
print(json_file)
|
||||
print(mw.getTracebackInfo())
|
||||
|
||||
start = (page - 1) * pageSize
|
||||
@@ -927,14 +941,14 @@ class plugins_api:
|
||||
|
||||
return plugins_info
|
||||
|
||||
def getPluginList(self, sType, sPage=1, sPageSize=10):
|
||||
# print sType, sPage, sPageSize
|
||||
def getPluginList(self, sType, kw='', sPage=1, sPageSize=10):
|
||||
# print(sType, kw, sPage, sPageSize)
|
||||
|
||||
ret = {}
|
||||
ret['type'] = json.loads(mw.readFile(self.__type))
|
||||
# plugins_info = self.getAllListThread(sType)
|
||||
# plugins_info = self.getAllListProcess(sType)
|
||||
data = self.getAllListPage(sType, sPage, sPageSize)
|
||||
data = self.getAllListPage(sType, kw, sPage, sPageSize)
|
||||
ret['data'] = data[0]
|
||||
|
||||
args = {}
|
||||
@@ -1016,8 +1030,11 @@ class plugins_api:
|
||||
|
||||
# shell 调用
|
||||
def run(self, name, func, version='', args='', script='index'):
|
||||
path = self.__plugin_dir + \
|
||||
'/' + name + '/' + script + '.py'
|
||||
|
||||
path = self.__plugin_dir + '/' + name + '/' + script + '.py'
|
||||
if not os.path.exists(path):
|
||||
path = self.__plugin_dir + '/' + name + '/' + name + '.py'
|
||||
|
||||
py = 'python3 ' + path
|
||||
|
||||
if args == '':
|
||||
|
||||
+125
-56
@@ -101,19 +101,31 @@ class site_api:
|
||||
limit = request.form.get('limit', '10')
|
||||
p = request.form.get('p', '1')
|
||||
type_id = request.form.get('type_id', '0').strip()
|
||||
search = request.form.get('search', '').strip()
|
||||
|
||||
start = (int(p) - 1) * (int(limit))
|
||||
|
||||
siteM = mw.M('sites').field('id,name,path,status,ps,addtime,edate')
|
||||
if type_id != '' and int(type_id) >= 0:
|
||||
siteM.where('type_id=?', (type_id,))
|
||||
|
||||
sql_where = ''
|
||||
if search != '':
|
||||
sql_where = " name like '%" + search + "%' or ps like '%" + search + "%' "
|
||||
|
||||
if type_id != '' and int(type_id) >= 0 and search != '':
|
||||
sql_where = sql_where + " and type_id=" + type_id + ""
|
||||
elif type_id != '' and int(type_id) >= 0:
|
||||
sql_where = " type_id=" + type_id
|
||||
|
||||
if sql_where != '':
|
||||
siteM.where(sql_where)
|
||||
|
||||
_list = siteM.limit((str(start)) + ',' +
|
||||
limit).order('id desc').select()
|
||||
|
||||
for i in range(len(_list)):
|
||||
_list[i]['backup_count'] = mw.M('backup').where(
|
||||
"pid=? AND type=?", (_list[i]['id'], 0)).count()
|
||||
if _list != None:
|
||||
for i in range(len(_list)):
|
||||
_list[i]['backup_count'] = mw.M('backup').where(
|
||||
"pid=? AND type=?", (_list[i]['id'], 0)).count()
|
||||
|
||||
_ret = {}
|
||||
_ret['data'] = _list
|
||||
@@ -775,6 +787,9 @@ class site_api:
|
||||
mw.execShell('echo "lets" > "' + path + '/README"')
|
||||
elif ssl_type == 'acme':
|
||||
ssl_acme_dir = mw.getAcmeDir() + '/' + site_name
|
||||
if not os.path.exists(ssl_acme_dir):
|
||||
ssl_acme_dir = mw.getAcmeDir() + '/' + site_name + '_ecc'
|
||||
|
||||
acme_csrpath = ssl_acme_dir + '/fullchain.cer'
|
||||
acme_keypath = ssl_acme_dir + '/' + site_name + '.key'
|
||||
if mw.md5(mw.readFile(acme_csrpath)) == mw.md5(mw.readFile(csr_path)):
|
||||
@@ -1420,6 +1435,8 @@ class site_api:
|
||||
data['data'] = mw.readFile(filename)
|
||||
data['rlist'] = []
|
||||
for ds in os.listdir(self.rewritePath):
|
||||
if ds[0:1] == '.':
|
||||
continue
|
||||
if ds == 'list.txt':
|
||||
continue
|
||||
data['rlist'].append(ds[0:len(ds) - 5])
|
||||
@@ -1853,19 +1870,16 @@ class site_api:
|
||||
if _id == '' or _siteName == '':
|
||||
return mw.returnJson(False, "必填项不能为空!")
|
||||
|
||||
_old_config = mw.readFile(
|
||||
"{}/{}/{}.conf".format(self.proxyPath, _siteName, _id))
|
||||
if _old_config == False:
|
||||
return mw.returnJson(False, "非法操作")
|
||||
|
||||
mw.writeFile("{}/{}/{}.conf".format(self.proxyPath,
|
||||
_siteName, _id), _config)
|
||||
proxy_file = "{}/{}/{}.conf".format(self.proxyPath, _siteName, _id)
|
||||
mw.backFile(proxy_file)
|
||||
mw.writeFile(proxy_file, _config)
|
||||
rule_test = mw.checkWebConfig()
|
||||
if rule_test != True:
|
||||
mw.writeFile("{}/{}/{}.conf".format(self.proxyPath,
|
||||
_siteName, _id), _old_config)
|
||||
mw.restoreFile(proxy_file)
|
||||
mw.removeBackFile(proxy_file)
|
||||
return mw.returnJson(False, "OpenResty 配置测试不通过, 请重试: {}".format(rule_test))
|
||||
|
||||
mw.removeBackFile(proxy_file)
|
||||
self.operateRedirectConf(_siteName, 'start')
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, "ok")
|
||||
@@ -1906,21 +1920,20 @@ class site_api:
|
||||
_from = request.form.get('from', '')
|
||||
_to = request.form.get('to', '')
|
||||
_host = request.form.get('host', '')
|
||||
_name = request.form.get('name', '')
|
||||
_open_proxy = request.form.get('open_proxy', '')
|
||||
_open_cache = request.form.get('open_cache', '')
|
||||
_cache_time = request.form.get('cache_time', '')
|
||||
_id = request.form.get('id', '')
|
||||
|
||||
if _siteName == "" or _from == "" or _to == "" or _host == "":
|
||||
# print(_name, _siteName, _from, _to, _host)
|
||||
if _name == "" or _siteName == "" or _from == "" or _to == "" or _host == "":
|
||||
return mw.returnJson(False, "必填项不能为空")
|
||||
|
||||
data_path = self.getProxyDataPath(_siteName)
|
||||
data_content = mw.readFile(
|
||||
data_path) if os.path.exists(data_path) else ""
|
||||
data = json.loads(data_content) if data_content != "" else []
|
||||
|
||||
rep = "http(s)?\:\/\/([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9][a-zA-Z0-9]{0,62})+.?"
|
||||
if not re.match(rep, _to):
|
||||
return mw.returnJson(False, "错误的目标地址!")
|
||||
|
||||
# _to = _to.strip("/")
|
||||
# get host from url
|
||||
try:
|
||||
if _host == "$host":
|
||||
@@ -1929,7 +1942,11 @@ class site_api:
|
||||
except:
|
||||
return mw.returnJson(False, "错误的目标地址")
|
||||
|
||||
# location ~* ^{from}(.*)$ {
|
||||
proxy_site_path = self.getProxyDataPath(_siteName)
|
||||
data_content = mw.readFile(
|
||||
proxy_site_path) if os.path.exists(proxy_site_path) else ""
|
||||
data = json.loads(data_content) if data_content != "" else []
|
||||
|
||||
tpl = "#PROXY-START\n\
|
||||
location ^~ {from} {\n\
|
||||
proxy_pass {to};\n\
|
||||
@@ -1937,12 +1954,29 @@ location ^~ {from} {\n\
|
||||
proxy_set_header X-Real-IP $remote_addr;\n\
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n\
|
||||
proxy_set_header REMOTE-HOST $remote_addr;\n\
|
||||
proxy_set_header Upgrade $http_upgrade;\n\
|
||||
proxy_set_header Connection $connection_upgrade;\n\
|
||||
proxy_http_version 1.1;\n\
|
||||
\n\
|
||||
add_header X-Cache $upstream_cache_status;\n\
|
||||
proxy_ignore_headers Set-Cookie Cache-Control expires;\n\
|
||||
add_header Cache-Control no-cache;\n\
|
||||
\n\
|
||||
set $static_files_app 0;\n\
|
||||
{proxy_cache}\n\
|
||||
}\n\
|
||||
# PROXY-END"
|
||||
|
||||
tpl_proxy_cache = "\n\
|
||||
if ( $uri ~* \"\.(gif|png|jpg|css|js|woff|woff2)$\" )\n\
|
||||
{\n\
|
||||
expires {cache_time}m;\n\
|
||||
}\n\
|
||||
proxy_ignore_headers Set-Cookie Cache-Control expires;\n\
|
||||
proxy_cache mw_cache;\n\
|
||||
proxy_cache_key \"$host$uri$is_args$args\";\n\
|
||||
proxy_cache_valid 200 304 301 302 {cache_time}m;\n\
|
||||
"
|
||||
|
||||
tpl_proxy_nocache = "\n\
|
||||
set $static_files_app 0; \n\
|
||||
if ( $uri ~* \"\.(gif|png|jpg|css|js|woff|woff2)$\" )\n\
|
||||
{\n\
|
||||
set $static_files_app 1;\n\
|
||||
@@ -1952,8 +1986,7 @@ location ^~ {from} {\n\
|
||||
{\n\
|
||||
add_header Cache-Control no-cache;\n\
|
||||
}\n\
|
||||
}\n\
|
||||
#PROXY-END"
|
||||
"
|
||||
|
||||
# replace
|
||||
if _from[0] != '/':
|
||||
@@ -1961,28 +1994,69 @@ location ^~ {from} {\n\
|
||||
tpl = tpl.replace("{from}", _from, 999)
|
||||
tpl = tpl.replace("{to}", _to)
|
||||
tpl = tpl.replace("{host}", _host, 999)
|
||||
tpl = tpl.replace("{cache_time}", _cache_time, 999)
|
||||
|
||||
_id = mw.md5("{}+{}+{}".format(_from, _to, _siteName))
|
||||
for item in data:
|
||||
if item["id"] == _id:
|
||||
return mw.returnJson(False, "已存在该规则!")
|
||||
if item["from"] == _from:
|
||||
return mw.returnJson(False, "代理目录已存在!")
|
||||
data.append({
|
||||
"from": _from,
|
||||
"to": _to,
|
||||
"host": _host,
|
||||
"id": _id
|
||||
})
|
||||
if _open_cache == 'on':
|
||||
tpl_proxy_cache = tpl_proxy_cache.replace(
|
||||
"{cache_time}", _cache_time, 999)
|
||||
tpl = tpl.replace("{proxy_cache}", tpl_proxy_cache, 999)
|
||||
else:
|
||||
tpl = tpl.replace("{proxy_cache}", tpl_proxy_nocache, 999)
|
||||
|
||||
proxy_action = 'add'
|
||||
if _id == "":
|
||||
_id = mw.md5("{}".format(_name))
|
||||
else:
|
||||
proxy_action = 'edit'
|
||||
|
||||
conf_proxy = "{}/{}.conf".format(self.getProxyPath(_siteName), _id)
|
||||
conf_bk = "{}/{}.conf.txt".format(self.getProxyPath(_siteName), _id)
|
||||
|
||||
mw.writeFile(conf_proxy, tpl)
|
||||
|
||||
rule_test = mw.checkWebConfig()
|
||||
if rule_test != True:
|
||||
os.remove(conf_proxy)
|
||||
return mw.returnJson(False, "OpenResty配置测试不通过, 请重试: {}".format(rule_test))
|
||||
|
||||
if proxy_action == "add":
|
||||
# 添加代理
|
||||
_id = mw.md5("{}".format(_name))
|
||||
for item in data:
|
||||
if item["name"] == _name:
|
||||
return mw.returnJson(False, "名称重复!")
|
||||
if item["from"] == _from:
|
||||
return mw.returnJson(False, "代理目录已存在!")
|
||||
data.append({
|
||||
"name": _name,
|
||||
"from": _from,
|
||||
"to": _to,
|
||||
"host": _host,
|
||||
"open_cache": _open_cache,
|
||||
"open_proxy": _open_proxy,
|
||||
"cache_time": _cache_time,
|
||||
"id": _id,
|
||||
})
|
||||
else:
|
||||
# 修改代理
|
||||
dindex = -1
|
||||
for x in range(len(data)):
|
||||
if data[x]["id"] == _id:
|
||||
dindex = x
|
||||
break
|
||||
if dindex < 0:
|
||||
return mw.returnJson(False, "异常请求")
|
||||
data[dindex]['from'] = _from
|
||||
data[dindex]['to'] = _to
|
||||
data[dindex]['host'] = _host
|
||||
data[dindex]['open_cache'] = _open_cache
|
||||
data[dindex]['open_proxy'] = _open_proxy
|
||||
data[dindex]['cache_time'] = _cache_time
|
||||
|
||||
conf_file = "{}/{}.conf".format(self.getProxyPath(_siteName), _id)
|
||||
if _open_proxy != 'on':
|
||||
conf_file = "{}/{}.conf.txt".format(
|
||||
self.getProxyPath(_siteName), _id)
|
||||
|
||||
mw.writeFile(data_path, json.dumps(data))
|
||||
mw.writeFile(conf_file, tpl)
|
||||
os.rename(conf_proxy, conf_bk)
|
||||
|
||||
mw.writeFile(proxy_site_path, json.dumps(data))
|
||||
self.operateProxyConf(_siteName, 'start')
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, "ok", {"hash": _id})
|
||||
@@ -2013,10 +2087,10 @@ location ^~ {from} {\n\
|
||||
self.getProxyPath(_siteName), _id)
|
||||
mw.execShell(cmd)
|
||||
except:
|
||||
return mw.returnJson(False, "删除失败!")
|
||||
return mw.returnJson(False, "删除反代失败!")
|
||||
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, "删除成功!")
|
||||
return mw.returnJson(True, "删除反代成功!")
|
||||
|
||||
def getSiteTypesApi(self):
|
||||
# 取网站分类
|
||||
@@ -2083,7 +2157,7 @@ location ^~ {from} {\n\
|
||||
|
||||
##### ----- end ----- ###
|
||||
|
||||
# 域名编码转换
|
||||
# 域名编码转换
|
||||
def toPunycode(self, domain):
|
||||
import re
|
||||
if sys.version_info[0] == 2:
|
||||
@@ -2091,7 +2165,7 @@ location ^~ {from} {\n\
|
||||
tmp = domain.split('.')
|
||||
newdomain = ''
|
||||
for dkey in tmp:
|
||||
# 匹配非ascii字符
|
||||
# 匹配非ascii字符
|
||||
match = re.search(u"[\x80-\xff]+", dkey)
|
||||
if not match:
|
||||
newdomain += dkey + '.'
|
||||
@@ -2646,7 +2720,7 @@ location ^~ {from} {\n\
|
||||
mw.writeLog('TYPE_SITE', '设置成功,站点到期后将自动停止!', (siteName, edate))
|
||||
return mw.returnJson(True, '设置成功,站点到期后将自动停止!')
|
||||
|
||||
# ssl相关方法 start
|
||||
# ssl相关方法 start
|
||||
def setSslConf(self, siteName):
|
||||
file = self.getHostConf(siteName)
|
||||
conf = mw.readFile(file)
|
||||
@@ -2745,9 +2819,4 @@ location ^~ {from} {\n\
|
||||
mw.execShell("chattr +i " + filename)
|
||||
|
||||
return mw.returnJson(True, '已打开防跨站设置!')
|
||||
|
||||
# 转换时间
|
||||
def strfToTime(self, sdate):
|
||||
import time
|
||||
return time.strftime('%Y-%m-%d', time.strptime(sdate, '%b %d %H:%M:%S %Y %Z'))
|
||||
# ssl相关方法 end
|
||||
# ssl相关方法 end
|
||||
|
||||
@@ -755,6 +755,8 @@ class system_api:
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
|
||||
P_VER=`python3 -V | awk '{print $2}'`
|
||||
|
||||
if [ ! -f /www/server/mdserver-web/bin/activate ];then
|
||||
cd /www/server/mdserver-web && python3 -m venv .
|
||||
cd /www/server/mdserver-web && source /www/server/mdserver-web/bin/activate
|
||||
@@ -769,6 +771,14 @@ if [ ! -z "$cn" ];then
|
||||
fi
|
||||
|
||||
cd /www/server/mdserver-web && pip3 install -r /www/server/mdserver-web/requirements.txt -i $PIPSRC
|
||||
|
||||
P_VER_D=`echo "$P_VER"|awk -F '.' '{print $1}'`
|
||||
P_VER_M=`echo "$P_VER"|awk -F '.' '{print $2}'`
|
||||
NEW_P_VER=${P_VER_D}.${P_VER_M}
|
||||
|
||||
if [ -f /www/server/mdserver-web/version/r${NEW_P_VER}.txt ];then
|
||||
cd /www/server/mdserver-web && pip3 install -r /www/server/mdserver-web/version/r${NEW_P_VER}.txt -i $PIPSRC
|
||||
fi
|
||||
'''
|
||||
os.system(update_env)
|
||||
self.restartMw()
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# coding:utf-8
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# MW-Linux面板
|
||||
# ---------------------------------------------------------------------------------
|
||||
# copyright (c) 2018-∞(https://github.com/midoks/mdserver-web) All rights reserved.
|
||||
# ---------------------------------------------------------------------------------
|
||||
# Author: midoks <midoks@163.com>
|
||||
# ---------------------------------------------------------------------------------
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# VIP用户管理
|
||||
# ---------------------------------------------------------------------------------
|
||||
|
||||
import mw
|
||||
|
||||
from flask import request
|
||||
import requests
|
||||
|
||||
|
||||
class vip_api:
|
||||
|
||||
api_url = 'https://wo.midoks.me/api/wp-json/vip'
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def loginApi(self):
|
||||
username = request.form.get('username', '')
|
||||
password = request.form.get('password', '')
|
||||
password = mw.aesEncrypt(password)
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
}
|
||||
|
||||
print("name:", str(username))
|
||||
print("pwd:", str(password))
|
||||
args = {
|
||||
'name': username,
|
||||
'pass': password
|
||||
}
|
||||
data = requests.post(self.api_url + '/v1/login',
|
||||
data=args, headers=headers)
|
||||
|
||||
print(data.text)
|
||||
|
||||
return mw.returnJson(False, "测试中!")
|
||||
@@ -0,0 +1,43 @@
|
||||
# coding: utf-8
|
||||
|
||||
import smtplib
|
||||
|
||||
from email import encoders
|
||||
from email.header import Header
|
||||
from email.mime.text import MIMEText
|
||||
from email.utils import parseaddr, formataddr
|
||||
|
||||
|
||||
def _format_addr(s):
|
||||
name, addr = parseaddr(s)
|
||||
return formataddr((Header(name, 'utf-8').encode(), addr))
|
||||
|
||||
|
||||
def send(smtp_host, smtp_port, username, password, to_mail, subject, content):
|
||||
|
||||
smtp = smtplib.SMTP()
|
||||
smtp.connect(smtp_host, port=smtp_port)
|
||||
smtp.login(user=username, password=password)
|
||||
|
||||
msg = MIMEText(content, 'plain', 'utf-8')
|
||||
msg['From'] = _format_addr(username)
|
||||
msg['To'] = _format_addr(to_mail)
|
||||
msg['Subject'] = Header(subject, 'utf-8').encode()
|
||||
|
||||
smtp.sendmail(from_addr=username, to_addrs=to_mail, msg=msg.as_string())
|
||||
return True
|
||||
|
||||
|
||||
def sendSSL(smtp_host, smtp_port, username, password, to_mail, subject, content):
|
||||
|
||||
smtp = smtplib.SMTP_SSL(smtp_host, port=smtp_port)
|
||||
smtp.login(user=username, password=password)
|
||||
|
||||
msg = MIMEText(content, 'plain', 'utf-8')
|
||||
msg['From'] = _format_addr(username)
|
||||
msg['To'] = _format_addr(to_mail)
|
||||
msg['Subject'] = Header(subject, 'utf-8').encode()
|
||||
|
||||
smtp.sendmail(from_addr=username, to_addrs=to_mail, msg=msg.as_string())
|
||||
smtp.quit()
|
||||
return True
|
||||
@@ -16,7 +16,7 @@ mw_start_task()
|
||||
{
|
||||
isStart=$(ps aux |grep 'task.py'|grep -v grep|awk '{print $2}')
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting mw-tasks... \c"
|
||||
echo -e "starting mw-tasks... \c"
|
||||
cd $DIR && python3 task.py >> ${DIR}/logs/task.log 2>&1 &
|
||||
sleep 0.3
|
||||
isStart=$(ps aux |grep 'task.py'|grep -v grep|awk '{print $2}')
|
||||
@@ -30,7 +30,7 @@ mw_start_task()
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting mw-tasks... mw-tasks (pid $(echo $isStart)) already running"
|
||||
echo "starting mw-tasks... mw-tasks (pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
+20
-17
@@ -16,6 +16,7 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
| CentOS 9 Stream |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |
|
||||
| Debian 12.0 |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |
|
||||
@@ -28,23 +29,24 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
|
||||
|
||||
|
||||
| 系统名称 |PHP53 |PHP54 |PHP55 |PHP56 |PHP70 |PHP71 |PHP72 |PHP73 |PHP74 |PHP80 |PHP81 |
|
||||
| ----------------- |-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|
|
||||
| CentOS 7.9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 31 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 32 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| AlmaLinux 9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| RockyLinux 8.6 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Arch Linux |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| openSUSE 15.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| 系统名称 |PHP53 |PHP54 |PHP55 |PHP56 |PHP70 |PHP71 |PHP72 |PHP73 |PHP74 |PHP80 |PHP81 |PHP82 |
|
||||
| ----------------- |-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|
|
||||
| CentOS 7.9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 8 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Debian 12 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 31 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Fedora 32 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| AlmaLinux 9 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| RockyLinux 8.6 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| Arch Linux |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
| openSUSE 15.4 |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |✅ |
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +58,7 @@ cd /www/server/mdserver-web/plugins/php/versions && bash all_test.sh
|
||||
| CentOS 9 Stream |✅ |✅ |✅ |✅ |
|
||||
| Debian 10.3 |✅ |✅ |✅ |✅ |
|
||||
| Debian 11.3 |✅ |✅ |✅ |✅ |
|
||||
| Debian 12 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 18.04 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 20.04 |✅ |✅ |✅ |✅ |
|
||||
| Ubuntu 22.04 |✅ |✅ |✅ |✅ |
|
||||
|
||||
@@ -46,9 +46,8 @@ CREATE TABLE IF NOT EXISTS `firewall` (
|
||||
|
||||
INSERT INTO `firewall` (`id`, `port`, `ps`, `addtime`) VALUES
|
||||
(1, '80', '网站默认端口', '0000-00-00 00:00:00'),
|
||||
(2, '22', 'SSH远程管理服务', '0000-00-00 00:00:00'),
|
||||
(3, '443', 'HTTPS', '0000-00-00 00:00:00'),
|
||||
(4, '888', 'phpMyAdmin默认端口', '0000-00-00 00:00:00');
|
||||
(2, '443', 'HTTPS', '0000-00-00 00:00:00'),
|
||||
(3, '888', 'phpMyAdmin默认端口', '0000-00-00 00:00:00');
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-9
@@ -39,20 +39,13 @@ server
|
||||
allow all;
|
||||
}
|
||||
|
||||
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf)$
|
||||
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf|js|css)$
|
||||
{
|
||||
expires 30d;
|
||||
error_log off;
|
||||
error_log /dev/null;
|
||||
access_log /dev/null;
|
||||
}
|
||||
|
||||
location ~ .*\\.(js|css)?$
|
||||
{
|
||||
expires 12h;
|
||||
error_log off;
|
||||
access_log /dev/null;
|
||||
}
|
||||
|
||||
access_log {$LOGPATH}/{$SERVER_NAME}.log main;
|
||||
error_log {$LOGPATH}/{$SERVER_NAME}.error.log;
|
||||
}
|
||||
@@ -35,18 +35,11 @@ server
|
||||
allow all;
|
||||
}
|
||||
|
||||
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf)$
|
||||
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf|js|css)$
|
||||
{
|
||||
expires 30d;
|
||||
error_log off;
|
||||
error_log /dev/null;
|
||||
access_log /dev/null;
|
||||
}
|
||||
|
||||
location ~ .*\\.(js|css)?$
|
||||
{
|
||||
expires 12h;
|
||||
error_log off;
|
||||
access_log /dev/null;
|
||||
expires 30d;
|
||||
}
|
||||
|
||||
access_log {$LOGPATH}/{$SERVER_MAIN}_{$DIRBIND}.log;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
存放VIP关键数据
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
Executable
+58
@@ -0,0 +1,58 @@
|
||||
<style type="text/css">
|
||||
|
||||
.docker-sub {
|
||||
border-bottom: 1px solid #ccc;
|
||||
height: 30px;
|
||||
line-height: 30px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.docker-sub .on {
|
||||
border-bottom: 2px solid #20a53a;
|
||||
color: #20a53a;
|
||||
font-weight: bold;
|
||||
font-family: "宋体";
|
||||
}
|
||||
.docker-sub span {
|
||||
display: inline-block;
|
||||
font-size: 14px;
|
||||
height: 30px;
|
||||
padding: 0 25px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.docker-environments {
|
||||
resize: none;
|
||||
width: 330px;
|
||||
height: 80px;
|
||||
line-height: 20px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #ddd;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="bt-form">
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('docker');">服务</p>
|
||||
<p onclick="pluginInitD('docker');">自启动</p>
|
||||
<p onclick="dockerConList();">容器列表</p>
|
||||
<p onclick="dockerImageList();">镜像列表</p>
|
||||
<p onclick="dockerImageOutput();">镜像导出</p>
|
||||
<p onclick="dockerIpList();">IP地址池</p>
|
||||
<p onclick="repoList();">仓库</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
resetPluginWinHeight(400);
|
||||
$.getScript( "/plugins/file?name=docker&f=js/docker.js", function(){
|
||||
pluginService('docker', $('.plugin_version').attr('version'));
|
||||
});
|
||||
</script>
|
||||
Executable
+860
@@ -0,0 +1,860 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import json
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
import docker
|
||||
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
def getDClient():
|
||||
try:
|
||||
client = docker.from_env()
|
||||
except Exception as e:
|
||||
client = docker.DockerClient(
|
||||
base_url='unix:///Users/midoks/.docker/run/docker.sock')
|
||||
return client
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'docker'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getConf():
|
||||
path = getServerDir() + "/redis.conf"
|
||||
return path
|
||||
|
||||
|
||||
def getConfTpl():
|
||||
path = getPluginDir() + "/config/redis.conf"
|
||||
return path
|
||||
|
||||
|
||||
def getInitDTpl():
|
||||
path = getPluginDir() + "/init.d/" + getPluginName() + ".tpl"
|
||||
return path
|
||||
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
|
||||
def checkArgs(self, data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
print(data[i])
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
|
||||
def status():
|
||||
data = mw.execShell(
|
||||
"ps -ef|grep docker |grep -v grep | grep -v python | grep -v mdserver-web | awk '{print $2}'")
|
||||
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
|
||||
def initDreplace():
|
||||
return ''
|
||||
|
||||
|
||||
def dockerOp(method):
|
||||
file = initDreplace()
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
data = mw.execShell('systemctl ' + method + ' docker')
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[1]
|
||||
return 'fail'
|
||||
|
||||
|
||||
def start():
|
||||
return dockerOp('start')
|
||||
|
||||
|
||||
def stop():
|
||||
return dockerOp('stop')
|
||||
|
||||
|
||||
def restart():
|
||||
status = dockerOp('restart')
|
||||
|
||||
log_file = runLog()
|
||||
mw.execShell("echo '' > " + log_file)
|
||||
return status
|
||||
|
||||
|
||||
def reload():
|
||||
return dockerOp('reload')
|
||||
|
||||
|
||||
def initdStatus():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
shell_cmd = 'systemctl status ' + \
|
||||
getPluginName() + ' | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(shell_cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdInstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl enable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
|
||||
def initdUinstall():
|
||||
if mw.isAppleSystem():
|
||||
return "Apple Computer does not support"
|
||||
|
||||
mw.execShell('systemctl disable ' + getPluginName())
|
||||
return 'ok'
|
||||
|
||||
# UTC时间转换为时间戳
|
||||
|
||||
|
||||
def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S'):
|
||||
import pytz
|
||||
import datetime
|
||||
import time
|
||||
local_tz = pytz.timezone('Asia/Chongqing')
|
||||
local_format = "%Y-%m-%d %H:%M"
|
||||
utc_dt = datetime.datetime.strptime(utc_time_str, utc_format)
|
||||
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
|
||||
time_str = local_dt.strftime(local_format)
|
||||
return int(time.mktime(time.strptime(time_str, local_format)))
|
||||
|
||||
|
||||
def conList():
|
||||
c = getDClient()
|
||||
clist = c.containers.list(all=True)
|
||||
conList = []
|
||||
for con in clist:
|
||||
tmp = con.attrs
|
||||
tmp['Created'] = utc_to_local(tmp['Created'].split('.')[0])
|
||||
conList.append(tmp)
|
||||
return conList
|
||||
|
||||
|
||||
def conListData():
|
||||
try:
|
||||
clist = conList()
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '未开启Docker')
|
||||
return mw.returnJson(True, 'ok', clist)
|
||||
|
||||
|
||||
def dockerRemoveCon():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
try:
|
||||
path_list = conFind.attrs['GraphDriver'][
|
||||
'Data']['LowerDir'].split(':')
|
||||
for i in path_list:
|
||||
mw.execShell('chattr -R -i %s' % i)
|
||||
except:
|
||||
pass
|
||||
conFind.remove(force=True)
|
||||
return mw.returnJson(True, '成功删除!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '删除失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerLogCon():
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
log = conFind.logs()
|
||||
if not isinstance(log, str):
|
||||
log = log.decode()
|
||||
return mw.returnJson(True, log)
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, 'Get Logs failed')
|
||||
|
||||
|
||||
def dockerRunCon():
|
||||
# 启动容器
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
conFind.start()
|
||||
return mw.returnJson(True, '启动成功!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '启动失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerStopCon():
|
||||
# 停止容器
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
if not conFind:
|
||||
return mw.returnJson(False, 'The specified container does not exist!')
|
||||
conFind.stop()
|
||||
return mw.returnJson(True, '停止成功!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '停止失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerExec():
|
||||
# 容器执行命令
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['Hostname'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
Hostname = args['Hostname']
|
||||
|
||||
debug_path = 'data/debug.pl'
|
||||
if os.path.exists(debug_path):
|
||||
return mw.returnJson(False, '开发模式不能进入!')
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
conFind = c.containers.get(Hostname)
|
||||
cmd = 'docker container exec -it %s /bin/sh' % Hostname
|
||||
return mw.returnJson(True, cmd)
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '连接失败!')
|
||||
|
||||
|
||||
def imageList():
|
||||
imageList = []
|
||||
c = getDClient()
|
||||
ilist = c.images.list()
|
||||
for image in ilist:
|
||||
tmp_attrs = image.attrs
|
||||
if len(tmp_attrs['RepoTags']) == 1:
|
||||
tmp_image = {}
|
||||
tmp_image['Id'] = tmp_attrs['Id'].split(':')[1][:12]
|
||||
tmp_image['RepoTags'] = tmp_attrs['RepoTags'][0]
|
||||
tmp_image['Size'] = tmp_attrs['Size']
|
||||
tmp_image['Labels'] = tmp_attrs['Config']['Labels']
|
||||
tmp_image['Comment'] = tmp_attrs['Comment']
|
||||
tmp_image['Created'] = utc_to_local(
|
||||
tmp_attrs['Created'].split('.')[0])
|
||||
imageList.append(tmp_image)
|
||||
else:
|
||||
for i in range(len(tmp_attrs['RepoTags'])):
|
||||
tmp_image = {}
|
||||
tmp_image['Id'] = tmp_attrs['Id'].split(':')[1][:12]
|
||||
tmp_image['RepoTags'] = tmp_attrs['RepoTags'][i]
|
||||
tmp_image['Size'] = tmp_attrs['Size']
|
||||
tmp_image['Labels'] = tmp_attrs['Config']['Labels']
|
||||
tmp_image['Comment'] = tmp_attrs['Comment']
|
||||
tmp_image['Created'] = utc_to_local(
|
||||
tmp_attrs['Created'].split('.')[0])
|
||||
imageList.append(tmp_image)
|
||||
imageList = sorted(imageList, key=lambda x: x['Created'], reverse=True)
|
||||
return imageList
|
||||
|
||||
|
||||
def dockerPull():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['images'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
images = args['images']
|
||||
if ':' in images:
|
||||
pass
|
||||
else:
|
||||
images = images + ':latest'
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
ret = c.images.pull(images)
|
||||
if ret:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
else:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
except:
|
||||
ret = mw.execShell('docker image pull %s' % images)
|
||||
if 'invalid' in ret[-1]:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
else:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
|
||||
|
||||
def dockerPlulPath(path):
|
||||
if not path and path == '':
|
||||
return mw.returnJson(False, 'Invalid address')
|
||||
|
||||
ret = mw.execShell('docker image pull %s' % path)
|
||||
if 'invalid' in ret[-1]:
|
||||
return mw.returnJson(False, '拉取失败,请检查镜像名称或是否需要登录docker进行下载')
|
||||
else:
|
||||
return mw.returnJson(True, '拉取成功!')
|
||||
|
||||
|
||||
def dockerPullReg():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = args['path']
|
||||
return dockerPlulPath(path)
|
||||
|
||||
|
||||
# 判断镜像是否存在
|
||||
def checkImage(path):
|
||||
image_list = imageList()
|
||||
for i in image_list:
|
||||
if path == i["RepoTags"]:
|
||||
return mw.returnData(False, '镜像已存在!')
|
||||
|
||||
|
||||
def dockerPullPrivateNew():
|
||||
# pull Dockr 官方镜像
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = args['path']
|
||||
check = checkImage(path)
|
||||
if check:
|
||||
return mw.getJson(check)
|
||||
|
||||
my_repo = repoList()
|
||||
if not my_repo:
|
||||
return mw.returnJson(False, '未登录任何私人存储库,请登录然后拉取')
|
||||
return dockerPlulPath(path)
|
||||
|
||||
|
||||
def imageListData():
|
||||
try:
|
||||
ilist = imageList()
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '未开启Docker')
|
||||
return mw.returnJson(True, 'ok', ilist)
|
||||
|
||||
|
||||
def dockerRemoveImage():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['imageId', 'repoTags'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
repoTags = args['repoTags']
|
||||
imageId = args['imageId']
|
||||
|
||||
c = getDClient()
|
||||
try:
|
||||
c.images.remove(repoTags)
|
||||
return mw.returnJson(True, '成功删除')
|
||||
except:
|
||||
try:
|
||||
c.images.remove(imageId)
|
||||
return mw.returnJson(True, '成功删除!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '删除失败, 当前镜像正在使用!')
|
||||
|
||||
|
||||
def getImageListFunc(dbname=''):
|
||||
bkDir = mw.getRootDir() + '/backup/docker'
|
||||
blist = os.listdir(bkDir)
|
||||
r = []
|
||||
|
||||
bname = 'db_' + dbname
|
||||
blen = len(bname)
|
||||
for x in blist:
|
||||
fbstr = x[0:blen]
|
||||
if fbstr == bname:
|
||||
r.append(x)
|
||||
return r
|
||||
|
||||
|
||||
def dockerImagePickDir():
|
||||
bkDir = mw.getRootDir() + '/backup/docker'
|
||||
return mw.returnJson(True, 'ok', bkDir)
|
||||
|
||||
|
||||
def dockerImagePickList():
|
||||
|
||||
bkDir = mw.getRootDir() + '/backup/docker'
|
||||
if not os.path.exists(bkDir):
|
||||
os.mkdir(bkDir)
|
||||
|
||||
r = os.listdir(bkDir)
|
||||
rr = []
|
||||
for x in range(0, len(r)):
|
||||
p = bkDir + '/' + r[x]
|
||||
data = {}
|
||||
data['name'] = r[x]
|
||||
|
||||
rsize = os.path.getsize(p)
|
||||
data['size'] = mw.toSize(rsize)
|
||||
|
||||
t = os.path.getctime(p)
|
||||
t = time.localtime(t)
|
||||
|
||||
data['time'] = time.strftime('%Y-%m-%d %H:%M:%S', t)
|
||||
rr.append(data)
|
||||
|
||||
data['file'] = p
|
||||
|
||||
return mw.returnJson(True, 'ok', rr)
|
||||
|
||||
|
||||
def dockerImagePickSave():
|
||||
# image 导出
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['images'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
bkDir = mw.getRootDir() + '/backup/docker/'
|
||||
images = args['images']
|
||||
try:
|
||||
file_name = bkDir + \
|
||||
str(time.strftime('%Y%m%d_%H%M%S', time.localtime())) + '.tar.gz'
|
||||
mw.execShell('docker image save %s | gzip > %s' %
|
||||
(images, file_name))
|
||||
return mw.returnJson(True, '导出镜像 {} 成功!'.format(file_name))
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '操作失败: ' + str(ex))
|
||||
|
||||
|
||||
def dockerImagePickLoad():
|
||||
# 镜像文件导入
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['file'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
try:
|
||||
file_path = args['file']
|
||||
if not os.path.exists(file_path):
|
||||
return mw.returnJson(False, '文件不存在')
|
||||
if file_path.endswith('.tar'):
|
||||
mw.execShell('docker image load < %s' % file_path)
|
||||
elif file_path.endswith('.tar.gz'):
|
||||
mw.execShell('gunzip -c %s | docker image load' % file_path)
|
||||
else:
|
||||
return mw.returnJson(False, '不支持改文件类型!')
|
||||
return mw.returnJson(True, '导入镜像文件成功!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '操作失败: ' + str(ex))
|
||||
|
||||
|
||||
def dockerLoginCheck(user_name, user_pass, registry):
|
||||
# 登陆验证
|
||||
cmd = 'docker login -u=%s -p %s %s' % (user_name, user_pass, registry)
|
||||
# print(cmd)
|
||||
login_test = mw.execShell(cmd)
|
||||
# print(login_test)
|
||||
ret = 'required$|Error'
|
||||
ret2 = re.findall(ret, login_test[-1])
|
||||
if len(ret2) == 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def getDockerIpListData():
|
||||
# 取IP列表
|
||||
path = getServerDir()
|
||||
ipConf = path + '/iplist.json'
|
||||
if not os.path.exists(ipConf):
|
||||
return []
|
||||
iplist = json.loads(mw.readFile(ipConf))
|
||||
return iplist
|
||||
|
||||
|
||||
def getDockerIpList():
|
||||
data = getDockerIpListData()
|
||||
return mw.returnJson(True, 'ok!', data)
|
||||
|
||||
|
||||
def dockerAddIP():
|
||||
# 添加IP
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['address', 'netmask', 'gateway'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = getServerDir()
|
||||
ipConf = path + '/iplist.json'
|
||||
if not os.path.exists(ipConf):
|
||||
iplist = []
|
||||
mw.writeFile(ipConf, json.dumps(iplist))
|
||||
|
||||
iplist = json.loads(mw.readFile(ipConf))
|
||||
ipInfo = {
|
||||
'address': args['address'],
|
||||
'netmask': args['netmask'],
|
||||
'gateway': args['gateway'],
|
||||
}
|
||||
iplist.append(ipInfo)
|
||||
mw.writeFile(ipConf, json.dumps(iplist))
|
||||
return mw.returnJson(True, '添加成功!')
|
||||
|
||||
|
||||
def dockerDelIP():
|
||||
# 删除IP
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['address'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
path = getServerDir()
|
||||
ipConf = path + '/iplist.json'
|
||||
if not os.path.exists(ipConf):
|
||||
return mw.returnJson(False, '指定的IP不存在。!')
|
||||
iplist = json.loads(mw.readFile(ipConf))
|
||||
newList = []
|
||||
for ipInfo in iplist:
|
||||
if ipInfo['address'] == args['address']:
|
||||
continue
|
||||
newList.append(ipInfo)
|
||||
mw.writeFile(ipConf, json.dumps(newList))
|
||||
return mw.returnJson(True, '成功删除!')
|
||||
|
||||
|
||||
def getDockerCreateInfo():
|
||||
# 取创建依赖
|
||||
import psutil
|
||||
data = {}
|
||||
data['images'] = imageList()
|
||||
data['memSize'] = int(psutil.virtual_memory().total / 1024 / 1024)
|
||||
data['iplist'] = getDockerIpListData()
|
||||
return mw.returnJson(True, 'ok!', data)
|
||||
|
||||
|
||||
def __release_port(port):
|
||||
from collections import namedtuple
|
||||
try:
|
||||
import firewall_api
|
||||
firewall_api.firewall_api().addAcceptPortArgs(port, 'docker', 'port')
|
||||
return port
|
||||
except Exception as e:
|
||||
return "Release failed {}".format(e)
|
||||
|
||||
|
||||
def dockerPortCheck():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['port'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
port = args['port']
|
||||
is_ok = IsPortExists(port)
|
||||
if is_ok:
|
||||
return mw.returnJson(True, 'ok')
|
||||
return mw.returnJson(False, 'fail')
|
||||
|
||||
|
||||
def IsPortExists(port):
|
||||
# 判断端口是否被占用
|
||||
ret = __check_dst_port(ip='localhost', port=port)
|
||||
ret2 = __check_dst_port(ip='0.0.0.0', port=port)
|
||||
if ret:
|
||||
return ret
|
||||
if not ret and ret2:
|
||||
return ret2
|
||||
if not ret and not ret2:
|
||||
return False
|
||||
|
||||
|
||||
def __check_dst_port(ip, port, timeout=3):
|
||||
# 端口检测
|
||||
import socket
|
||||
ok = True
|
||||
try:
|
||||
s = socket.socket()
|
||||
s.settimeout(timeout)
|
||||
s.connect((ip, port))
|
||||
s.close()
|
||||
except:
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def dockerCreateCon():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['environments', 'command',
|
||||
'entrypoint', 'image', 'mem_limit', 'ports', 'volumes'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
environments = args['environments']
|
||||
environments = environments.strip().split()
|
||||
|
||||
command = args['command']
|
||||
entrypoint = args['entrypoint']
|
||||
image = args['image']
|
||||
mem_limit = args['mem_limit']
|
||||
ports = args['ports']
|
||||
ports = ports.replace('[', '(').replace(']', ')')
|
||||
volumes = args['volumes']
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# print(args)
|
||||
try:
|
||||
|
||||
c = getDClient()
|
||||
conObject = c.containers.run(
|
||||
image=image,
|
||||
mem_limit=mem_limit + 'M',
|
||||
ports=eval(ports),
|
||||
auto_remove=False,
|
||||
command=command,
|
||||
detach=True,
|
||||
stdin_open=True,
|
||||
tty=True,
|
||||
entrypoint=entrypoint,
|
||||
privileged=True,
|
||||
volumes=json.loads(volumes),
|
||||
cpu_shares=10,
|
||||
environment=environments
|
||||
)
|
||||
if conObject:
|
||||
__release_port(ports)
|
||||
return mw.returnJson(True, '创建成功!')
|
||||
|
||||
return mw.returnJson(False, '创建失败!')
|
||||
except docker.errors.APIError as ex:
|
||||
return mw.returnJson(False, '创建失败!' + str(ex))
|
||||
|
||||
|
||||
def dockerLogin():
|
||||
args = getArgs()
|
||||
|
||||
# print(args)
|
||||
data = checkArgs(args, ['user', 'passwd', 'hub_name',
|
||||
'namespace', 'registry', 'repository_name'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
user_name = args['user']
|
||||
user_pass = args['passwd']
|
||||
registry = args['registry']
|
||||
hub_name = args['hub_name']
|
||||
namespace = args['namespace']
|
||||
repository_name = args['repository_name']
|
||||
|
||||
ret_status = dockerLoginCheck(user_name, user_pass, registry)
|
||||
path = getServerDir()
|
||||
if ret_status:
|
||||
user_file = path + '/user.json'
|
||||
user_info = mw.readFile(user_file)
|
||||
if not user_info:
|
||||
user_info = []
|
||||
else:
|
||||
user_info = json.loads(user_info)
|
||||
|
||||
ret = {}
|
||||
ret['user_name'] = user_name
|
||||
ret['user_pass'] = user_pass
|
||||
ret['registry'] = registry
|
||||
ret['hub_name'] = hub_name
|
||||
ret['namespace'] = namespace
|
||||
ret['repository_name'] = repository_name
|
||||
if not registry:
|
||||
ret['registry'] = "docker.io"
|
||||
user_info.append(ret)
|
||||
mw.writeFile(user_file, json.dumps(user_info))
|
||||
return mw.returnJson(True, '成功登录!')
|
||||
return mw.returnJson(False, '登录失败!')
|
||||
|
||||
|
||||
# 删除用户信息
|
||||
def delete_user_info(registry):
|
||||
path = getServerDir()
|
||||
user_file = path + '/user.json'
|
||||
user_info = mw.readFile(user_file)
|
||||
if user_info:
|
||||
user_info = json.loads(user_info)
|
||||
for i in range(len(user_info)):
|
||||
if registry in user_info[i].values():
|
||||
del(user_info[i])
|
||||
mw.writeFile(user_file, json.dumps(user_info))
|
||||
return True
|
||||
|
||||
|
||||
def dockerLogout():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['registry'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
registry = args['registry']
|
||||
if registry == "docker.io":
|
||||
registry = ""
|
||||
login_test = mw.execShell('docker logout %s' % registry)
|
||||
if registry == "":
|
||||
registry = "docker.io"
|
||||
ret = 'required$|Error'
|
||||
ret2 = re.findall(ret, login_test[-1])
|
||||
delete_user_info(registry)
|
||||
if len(ret2) == 0:
|
||||
return mw.returnJson(True, '退出成功')
|
||||
else:
|
||||
return mw.returnJson(True, '退出失败')
|
||||
|
||||
|
||||
def repoList():
|
||||
path = getServerDir()
|
||||
repostory_info = []
|
||||
user_file = path + '/user.json'
|
||||
|
||||
if os.path.exists(user_file):
|
||||
user_info = mw.readFile(user_file)
|
||||
user_info = json.loads(user_info)
|
||||
for i in user_info:
|
||||
tmp = {}
|
||||
tmp["hub_name"] = i["hub_name"]
|
||||
tmp["registry"] = i["registry"]
|
||||
tmp["namespace"] = i["namespace"]
|
||||
tmp['repository_name'] = i["repository_name"]
|
||||
repostory_info.append(tmp)
|
||||
|
||||
return mw.returnJson(True, 'ok', repostory_info)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
if func == 'status':
|
||||
print(status())
|
||||
elif func == 'start':
|
||||
print(start())
|
||||
elif func == 'stop':
|
||||
print(stop())
|
||||
elif func == 'restart':
|
||||
print(restart())
|
||||
elif func == 'reload':
|
||||
print(reload())
|
||||
elif func == 'initd_status':
|
||||
print(initdStatus())
|
||||
elif func == 'initd_install':
|
||||
print(initdInstall())
|
||||
elif func == 'initd_uninstall':
|
||||
print(initdUinstall())
|
||||
elif func == 'conf':
|
||||
print(getConf())
|
||||
elif func == 'con_list':
|
||||
print(conListData())
|
||||
elif func == 'docker_con_log':
|
||||
print(dockerLogCon())
|
||||
elif func == 'docker_remove_con':
|
||||
print(dockerRemoveCon())
|
||||
elif func == 'docker_run_con':
|
||||
print(dockerRunCon())
|
||||
elif func == 'docker_stop_con':
|
||||
print(dockerStopCon())
|
||||
elif func == 'docker_exec':
|
||||
print(dockerExec())
|
||||
elif func == 'docker_pull':
|
||||
print(dockerPull())
|
||||
elif func == 'docker_pull_reg':
|
||||
print(dockerPullReg())
|
||||
elif func == 'image_list':
|
||||
print(imageListData())
|
||||
elif func == 'image_pick_dir':
|
||||
print(dockerImagePickDir())
|
||||
elif func == 'image_pick_save':
|
||||
print(dockerImagePickSave())
|
||||
elif func == 'image_pick_load':
|
||||
print(dockerImagePickLoad())
|
||||
elif func == 'image_pick_list':
|
||||
print(dockerImagePickList())
|
||||
elif func == 'docker_get_iplist':
|
||||
print(getDockerIpList())
|
||||
elif func == 'docker_del_ip':
|
||||
print(dockerDelIP())
|
||||
elif func == 'docker_add_ip':
|
||||
print(dockerAddIP())
|
||||
elif func == 'get_docker_create_info':
|
||||
print(getDockerCreateInfo())
|
||||
elif func == 'docker_create_con':
|
||||
print(dockerCreateCon())
|
||||
elif func == 'docker_remove_image':
|
||||
print(dockerRemoveImage())
|
||||
elif func == 'docker_port_check':
|
||||
print(dockerPortCheck())
|
||||
elif func == 'docker_login':
|
||||
print(dockerLogin())
|
||||
elif func == 'docker_logout':
|
||||
print(dockerLogout())
|
||||
elif func == 'repo_list':
|
||||
print(repoList())
|
||||
else:
|
||||
print('error')
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"sort": 7,
|
||||
"ps": "Docker是一个开源的应用容器引擎",
|
||||
"name": "docker",
|
||||
"title": "Docker",
|
||||
"shell": "install.sh",
|
||||
"versions":["1.0"],
|
||||
"updates":["1.0"],
|
||||
"tip": "soft",
|
||||
"checks": "server/docker",
|
||||
"path": "server/docker",
|
||||
"display": 1,
|
||||
"author": "Zend",
|
||||
"date": "2017-04-01",
|
||||
"home": "https://docker.io",
|
||||
"doc1":"https://docker-py.readthedocs.io/",
|
||||
"type": 0,
|
||||
"pid": "2"
|
||||
}
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/docker && /bin/bash install.sh uninstall 1.0
|
||||
# cd /www/server/mdserver-web/plugins/docker && /bin/bash install.sh install 1.0
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
VERSION=$2
|
||||
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
|
||||
Install_Docker()
|
||||
{
|
||||
# which docker
|
||||
# if [ "$?" == "0" ];then
|
||||
# echo '安装已经完成docker' > $install_tmp
|
||||
# exit 0
|
||||
# fi
|
||||
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
if [ ! -d $serverPath/docker ];then
|
||||
curl -fsSL https://get.docker.com | bash
|
||||
mkdir -p $serverPath/docker
|
||||
fi
|
||||
|
||||
pip install docker
|
||||
pip install pytz
|
||||
|
||||
if [ -d $serverPath/docker ];then
|
||||
echo "${VERSION}" > $serverPath/docker/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/docker/index.py start
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/docker/index.py initd_install
|
||||
fi
|
||||
}
|
||||
|
||||
Uninstall_Docker()
|
||||
{
|
||||
CMD=yum
|
||||
which apt
|
||||
if [ "$?" == "0" ];then
|
||||
CMD=apt
|
||||
fi
|
||||
|
||||
if [ -f /usr/lib/systemd/system/docker.service ];then
|
||||
systemctl stop docker
|
||||
systemctl disable docker
|
||||
rm -rf /usr/lib/systemd/system/docker.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
$CMD remove -y docker docker-ce-cli containerd.io
|
||||
# docker-client \
|
||||
# docker-client-latest \
|
||||
# docker-common \
|
||||
# docker-latest \
|
||||
# docker-latest-logrotate \
|
||||
# docker-logrotate \
|
||||
# docker-selinux \
|
||||
# docker-engine-selinux \
|
||||
# docker-engine \
|
||||
# docker-ce
|
||||
|
||||
rm -rf $serverPath/docker
|
||||
echo "Uninstall_Docker" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_Docker
|
||||
else
|
||||
Uninstall_Docker
|
||||
fi
|
||||
Executable
+1084
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"ps": "Gitea 是一个开源社区驱动的轻量级代码托管解决方案。",
|
||||
"ps": "Gitea是一个开源社区驱动的轻量级代码托管解决方案。",
|
||||
"name": "gitea",
|
||||
"title": "Gitea",
|
||||
"versions": ["1.17.2"],
|
||||
"versions": ["1.17.2","1.18.5"],
|
||||
"tip": "soft",
|
||||
"install_pre_inspection":false,
|
||||
"uninstall_pre_inspection":true,
|
||||
|
||||
@@ -14,7 +14,7 @@ if [ -f ${rootPath}/bin/activate ];then
|
||||
fi
|
||||
|
||||
|
||||
URL_DOWNLOAD=https://dl.gitea.io/
|
||||
URL_DOWNLOAD=https://dl.gitea.com
|
||||
|
||||
|
||||
bash ${rootPath}/scripts/getos.sh
|
||||
|
||||
@@ -65,6 +65,7 @@ binlog-ignore-db = performance_schema
|
||||
|
||||
#slave
|
||||
log-slave-updates
|
||||
slave_skip_errors=1062
|
||||
#replicate-do-db
|
||||
replicate-ignore-db = information_schema
|
||||
replicate-ignore-db = performance_schema
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<script type="text/javascript">console.log($('.plugin_version').attr('version'));</script>
|
||||
<!-- <script type="text/javascript">console.log($('.plugin_version').attr('version'));</script> -->
|
||||
<p class="bgw" onclick="pluginService('mariadb', $('.plugin_version').attr('version'));">服务</p>
|
||||
<p onclick="pluginInitD('mariadb', $('.plugin_version').attr('version'));">自启动</p>
|
||||
<p onclick="pluginConfig('mariadb', $('.plugin_version').attr('version'));">配置文件</p>
|
||||
@@ -15,14 +15,12 @@
|
||||
<p onclick="dbList()">管理列表</p>
|
||||
<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="bt-w-con pd15" style="height:555px;overflow: auto;">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<style type="text/css">
|
||||
.db_list{
|
||||
padding: 0px 0 10px 0;
|
||||
@@ -52,10 +50,7 @@
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
|
||||
var loading = layer.msg("资源加载中...", { icon: 16, time: 0, shade: 0.3 });
|
||||
$.getScript( "/plugins/file?name=mariadb&f=js/mariadb.js", function(){
|
||||
layer.close(loading);
|
||||
pluginService('mariadb',$('.plugin_version').attr('version'));
|
||||
});
|
||||
</script>
|
||||
+260
-205
@@ -48,19 +48,19 @@ def getInitDFile():
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
t = args[0].strip('{').strip('}').strip()
|
||||
if (t == ''):
|
||||
return tmp
|
||||
t = t.split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
|
||||
return tmp
|
||||
|
||||
|
||||
@@ -107,6 +107,14 @@ def getDbPort():
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getDbServerId():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
rep = 'server-id\s*=\s*(.*)'
|
||||
tmp = re.search(rep, content)
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getSocketFile():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
@@ -664,15 +672,15 @@ def isSqlError(mysqlMsg):
|
||||
return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)")
|
||||
if "using password:" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!')
|
||||
if "1045" in mysqlMsg:
|
||||
if "1045," in mysqlMsg:
|
||||
return mw.returnJson(False, '连接错误!')
|
||||
if "SQL syntax" in mysqlMsg:
|
||||
return mw.returnJson(False, 'SQL语法错误!')
|
||||
if "Connection refused" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!')
|
||||
if "1133" in mysqlMsg:
|
||||
if "1133," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库用户不存在!')
|
||||
if "1007" in mysqlMsg:
|
||||
if "1007," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库已经存在!')
|
||||
return None
|
||||
|
||||
@@ -739,7 +747,7 @@ def importDbBackup():
|
||||
|
||||
pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')
|
||||
sock = getSocketFile()
|
||||
mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \
|
||||
mysql_cmd = getServerDir() + '/bin/mariadb -S ' + sock + ' -uroot -p' + pwd + \
|
||||
' ' + name + ' < ' + file_path_sql
|
||||
|
||||
# print(mysql_cmd)
|
||||
@@ -800,7 +808,7 @@ def importDbExternal():
|
||||
sock = getSocketFile()
|
||||
|
||||
os.environ["MYSQL_PWD"] = pwd
|
||||
mysql_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + \
|
||||
mysql_cmd = getServerDir() + '/bin/mariadb -S ' + sock + ' -uroot -p' + \
|
||||
pwd + ' ' + name + ' < ' + import_sql
|
||||
|
||||
# print(mysql_cmd)
|
||||
@@ -940,7 +948,7 @@ def getDbList():
|
||||
|
||||
|
||||
def syncGetDatabases():
|
||||
pdb = pMysqlDb()
|
||||
pdb = pMysqlDb('mysql')
|
||||
psdb = pSqliteDb('databases')
|
||||
data = pdb.query('show databases')
|
||||
isError = isSqlError(data)
|
||||
@@ -1706,12 +1714,14 @@ def getMasterStatus(version=''):
|
||||
data['mode'] = recognizeDbMode()
|
||||
data['status'] = master_status
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
pdb = pMysqlDb('mysql')
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) < 1:
|
||||
dlist = pdb.query("show all slaves status")
|
||||
|
||||
# print(dlist[0])
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
data['slave_status'] = True
|
||||
for v in dlist:
|
||||
if v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes':
|
||||
data['slave_status'] = True
|
||||
|
||||
return mw.returnJson(master_status, '设置成功', data)
|
||||
except Exception as e:
|
||||
@@ -1855,6 +1865,9 @@ def getMasterRepSlaveUserCmd(version):
|
||||
clist = psdb.field(f).where("username=?", (username,)).limit(
|
||||
'1').order('id desc').select()
|
||||
|
||||
if len(clist) == 0:
|
||||
return mw.returnJson(False, '错误同步账户!')
|
||||
|
||||
ip = mw.getLocalIp()
|
||||
port = getMyPort()
|
||||
db = pMysqlDb()
|
||||
@@ -1868,15 +1881,23 @@ def getMasterRepSlaveUserCmd(version):
|
||||
# 查找同步点
|
||||
# SELECT BINLOG_GTID_POS('master1-bin.000002', 561866201);
|
||||
|
||||
sid = getDbServerId()
|
||||
connection_name = ""
|
||||
if sid != '':
|
||||
connection_name = "'r{}' ".format(sid)
|
||||
|
||||
# MASTER_USE_GTID={current_pos|slave_pos|no}
|
||||
# current_pos 依赖-> select @@global.gtid_current_pos;
|
||||
# slave_pos 依赖-> select @@global.gtid_slave_pos;
|
||||
# no -> 啥都不依赖,保证多主同步成功。同步出现问题,根据日志查找问题。
|
||||
|
||||
if mode == "gtid":
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
sql = "CHANGE MASTER " + connection_name + "TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + "', " + "MASTER_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',MASTER_LOG_POS=" + \
|
||||
str(mstatus[0]["Position"]) + \
|
||||
",MASTER_USE_GTID=slave_pos,MASTER_CONNECT_RETRY=10;"
|
||||
"',MASTER_USE_GTID=no,MASTER_CONNECT_RETRY=10;"
|
||||
else:
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
sql = "CHANGE MASTER " + connection_name + "TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
@@ -2151,48 +2172,20 @@ def updateSlaveSSH(version=''):
|
||||
|
||||
|
||||
def getSlaveList(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
ret = []
|
||||
for x in range(0, len(dlist)):
|
||||
tmp = {}
|
||||
tmp['Master_User'] = dlist[x]["Master_User"]
|
||||
tmp['Master_Host'] = dlist[x]["Master_Host"]
|
||||
tmp['Master_Port'] = dlist[x]["Master_Port"]
|
||||
tmp['Master_Log_File'] = dlist[x]["Master_Log_File"]
|
||||
tmp['Slave_IO_Running'] = dlist[x]["Slave_IO_Running"]
|
||||
tmp['Slave_SQL_Running'] = dlist[x]["Slave_SQL_Running"]
|
||||
tmp['Last_Error'] = dlist[x]["Last_Error"]
|
||||
tmp['Last_IO_Error'] = dlist[x]["Last_IO_Error"]
|
||||
tmp['Last_SQL_Error'] = dlist[x]["Last_SQL_Error"]
|
||||
tmp['Slave_SQL_Running_State'] = dlist[x]["Slave_SQL_Running_State"]
|
||||
if len(dlist) == 0:
|
||||
dlist = db.query('show all slaves status')
|
||||
|
||||
tmp['Error'] = ''
|
||||
if tmp['Last_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_Error']
|
||||
|
||||
if tmp['Last_IO_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_IO_Error']
|
||||
|
||||
if tmp['Last_SQL_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_SQL_Error']
|
||||
|
||||
if tmp['Error'] == '':
|
||||
tmp['Error'] = tmp['Slave_SQL_Running_State']
|
||||
|
||||
ret.append(tmp)
|
||||
data = {}
|
||||
data['data'] = ret
|
||||
|
||||
data['data'] = dlist
|
||||
return mw.getJson(data)
|
||||
|
||||
|
||||
def getSlaveSyncCmd(version=''):
|
||||
|
||||
root = mw.getRunDir()
|
||||
cmd = 'cd ' + root + ' && python3 ' + root + \
|
||||
'/plugins/mysql/index.py do_full_sync {"db":"all"}'
|
||||
'/plugins/mariadb/index.py do_full_sync {"db":"all","sign":""}'
|
||||
return mw.returnJson(True, 'ok', cmd)
|
||||
|
||||
|
||||
@@ -2208,102 +2201,151 @@ def initSlaveStatus(version=''):
|
||||
return initSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def parseSlaveSyncCmd(cmd):
|
||||
a = {}
|
||||
vlist = cmd.split(',')
|
||||
|
||||
has_connection_name = vlist[0]
|
||||
|
||||
pattern_c = r"CHANGE MASTER \'(.*)\' TO MASTER_HOST"
|
||||
match_val = re.match(pattern_c, has_connection_name, re.I)
|
||||
if match_val:
|
||||
m_groups = match_val.groups()
|
||||
a['Connection_name'] = m_groups[0]
|
||||
|
||||
for i in vlist:
|
||||
tmp = i.strip()
|
||||
tmp_a = tmp.split(" ")
|
||||
real_tmp = tmp_a[len(tmp_a) - 1]
|
||||
kv = real_tmp.split("=")
|
||||
a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '')
|
||||
return a
|
||||
|
||||
|
||||
def initSlaveStatusSyncUser(version=''):
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) < 1:
|
||||
|
||||
slave_data = conn.field('id,ip,port,user,pass,mode,cmd').select()
|
||||
if len(slave_data) < 1:
|
||||
return mw.returnJson(False, '需要先添加同步用户配置!')
|
||||
|
||||
# print(data)
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
pdb = pMysqlDb()
|
||||
if len(slave_data) == 1:
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
u = data
|
||||
msg = ''
|
||||
|
||||
mode_name = 'classic'
|
||||
if u['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
pdb.query("stop slave")
|
||||
pdb.query("stop all slaves")
|
||||
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != mode_name:
|
||||
return mw.returnJson(False, '同步模式不一致!')
|
||||
for x in range(len(slave_data)):
|
||||
slave_t = slave_data[x]
|
||||
base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \
|
||||
slave_t['port'] + ",USER:" + slave_t['user']
|
||||
|
||||
# print(u['cmd'])
|
||||
t = db.query(u['cmd'])
|
||||
# print(t)
|
||||
db.query("start slave")
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
mode_name = 'classic'
|
||||
if slave_data[x]['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
|
||||
if local_mode != mode_name:
|
||||
msg += base_t + '->同步模式不一致'
|
||||
continue
|
||||
|
||||
cmd_sql = slave_t['cmd']
|
||||
if cmd_sql == '':
|
||||
msg += base_t + '->同步命令不能为空'
|
||||
continue
|
||||
|
||||
try:
|
||||
pinfo = parseSlaveSyncCmd(cmd_sql)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, base_t + '->CMD同步命令不合规范!')
|
||||
|
||||
pdb.query(cmd_sql)
|
||||
|
||||
pdb.query("start slave")
|
||||
pdb.query("start all slaves ")
|
||||
|
||||
if msg == '':
|
||||
msg = '初始化成功!'
|
||||
return mw.returnJson(True, msg)
|
||||
|
||||
|
||||
def initSlaveStatusSSH(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
if len(dlist) == 0:
|
||||
dlist = db.query('show all slaves status')
|
||||
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,port,id_rsa,db_user').find()
|
||||
ssh_list = conn.field('ip,port,id_rsa,db_user').select()
|
||||
|
||||
if len(data) < 1:
|
||||
if len(ssh_list) < 1:
|
||||
return mw.returnJson(False, '需要先配置【[主]SSH配置】!')
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh.txt"
|
||||
ip = data['ip']
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
|
||||
import paramiko
|
||||
paramiko.util.log_to_file('paramiko.log')
|
||||
ssh = paramiko.SSHClient()
|
||||
|
||||
try:
|
||||
for data in ssh_list:
|
||||
ip = data['ip']
|
||||
master_port = data['port']
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt"
|
||||
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
mw.execShell("chmod 600 " + SSH_PRIVATE_KEY)
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
|
||||
db_user = data['db_user']
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mariadb/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
cmd_data = json.loads(result)
|
||||
time.sleep(1)
|
||||
ssh.close()
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主]:' + cmd_data['msg'])
|
||||
try:
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '主【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
db_user = data['db_user']
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mariadb/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
if result.strip() == "":
|
||||
return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!')
|
||||
cmd_data = json.loads(result)
|
||||
time.sleep(1)
|
||||
ssh.close()
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg'])
|
||||
|
||||
u = cmd_data['data']['info']
|
||||
ps = u['username'] + "|" + u['password']
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
u = cmd_data['data']['info']
|
||||
ps = u['username'] + "|" + u['password']
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
db.query('stop all slaves')
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
# print(cmd)
|
||||
db.query(cmd)
|
||||
db.query("start slave")
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, 'SSH认证配置连接失败!' + str(e))
|
||||
# print(cmd)
|
||||
db.query(cmd)
|
||||
db.query("start slave")
|
||||
db.query("start all slaves")
|
||||
if os.path.exists(SSH_PRIVATE_KEY):
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e))
|
||||
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
|
||||
|
||||
@@ -2312,61 +2354,39 @@ def setSlaveStatus(version=''):
|
||||
if not os.path.exists(mode_file):
|
||||
return mw.returnJson(False, '需要先设置同步配置')
|
||||
|
||||
mode = mw.readFile(mode_file)
|
||||
if mode == 'ssh':
|
||||
return setSlaveStatusSSH(version)
|
||||
if mode == 'sync-user':
|
||||
return setSlaveStatusSyncUser(version)
|
||||
pdb = pMysqlDb()
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
dlist = pdb.query('show all slaves status')
|
||||
|
||||
|
||||
def setSlaveStatusSyncUser(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
for v in dlist:
|
||||
connection_name = ''
|
||||
cmd = "slave"
|
||||
if 'Connection_name' in v:
|
||||
connection_name = v['Connection_name']
|
||||
cmd = "slave '{}'".format(connection_name)
|
||||
|
||||
db.query("start slave")
|
||||
# db.query("start slave user='{}' password='{}';".format(user, apass))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def setSlaveStatusSSH(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加主服务命令或者执行[初始化]!')
|
||||
|
||||
# print(dlist)
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,ps').where("ip=?", (ip,)).find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
db.query("start slave")
|
||||
if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'):
|
||||
pdb.query("stop {}".format(cmd))
|
||||
else:
|
||||
pdb.query("start {}".format(cmd))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def deleteSlave(version=''):
|
||||
args = getArgs()
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('stop slave')
|
||||
dlist = db.query('reset slave all')
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
db.query("stop slave '{}'".format(sign))
|
||||
db.query("reset slave '{}' all".format(sign))
|
||||
else:
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
|
||||
@@ -2402,14 +2422,54 @@ def dumpMysqlData(version=''):
|
||||
|
||||
############### --- 重要 同步---- ###########
|
||||
|
||||
|
||||
def asyncTmpfile():
|
||||
path = '/tmp/mariadb_async_status.txt'
|
||||
return path
|
||||
|
||||
|
||||
def writeDbSyncStatus(data):
|
||||
path = '/tmp/db_async_status.txt'
|
||||
# status_data['code'] = 1
|
||||
# status_data['msg'] = '主服务器备份完成...'
|
||||
# status_data['progress'] = 30
|
||||
path = asyncTmpfile()
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
def fullSync(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db', 'begin'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sign = ''
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
|
||||
status_file = asyncTmpfile()
|
||||
if args['begin'] == '1':
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + \
|
||||
getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + \
|
||||
args['db'] + '","sign":"' + sign + '"} &'
|
||||
# print(cmd)
|
||||
mw.execShell(cmd)
|
||||
return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0})
|
||||
|
||||
if os.path.exists(status_file):
|
||||
c = mw.readFile(status_file)
|
||||
tmp = json.loads(c)
|
||||
if tmp['code'] == 1:
|
||||
sys_dump_sql = "/tmp/dump.sql"
|
||||
if os.path.exists(sys_dump_sql):
|
||||
dump_size = os.path.getsize(sys_dump_sql)
|
||||
tmp['msg'] = tmp['msg'] + ":" + "同步文件:" + mw.toSize(dump_size)
|
||||
c = json.dumps(tmp)
|
||||
|
||||
# if tmp['code'] == 6:
|
||||
# os.remove(status_file)
|
||||
return c
|
||||
|
||||
return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0})
|
||||
|
||||
|
||||
def doFullSync(version=''):
|
||||
mode_file = getSyncModeFile()
|
||||
if not os.path.exists(mode_file):
|
||||
@@ -2424,16 +2484,23 @@ def doFullSync(version=''):
|
||||
|
||||
def doFullSyncUser(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
# print(sync_sign, sync_db)
|
||||
db = pMysqlDb()
|
||||
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if sync_sign != '':
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
port = data['port']
|
||||
@@ -2442,12 +2509,12 @@ def doFullSyncUser(version=''):
|
||||
bak_file = '/tmp/tmp.sql'
|
||||
|
||||
writeDbSyncStatus({'code': 0, 'msg': '开始同步...', 'progress': 0})
|
||||
|
||||
writeDbSyncStatus({'code': 1, 'msg': '远程导出数据...', 'progress': 20})
|
||||
writeDbSyncStatus({'code': 1, 'msg': '远程导出数据...', 'progress': 10})
|
||||
|
||||
if not os.path.exists(bak_file):
|
||||
dump_sql_data = getServerDir() + "/bin/mysqldump --force --opt --default-character-set=utf8 --single-transaction -h" + ip + " -P" + \
|
||||
port + " -u" + user + " -p" + apass + " " + sync_db + " > " + bak_file
|
||||
print(dump_sql_data)
|
||||
mw.execShell(dump_sql_data)
|
||||
|
||||
writeDbSyncStatus({'code': 2, 'msg': '本地导入数据...', 'progress': 40})
|
||||
@@ -2458,24 +2525,38 @@ def doFullSyncUser(version=''):
|
||||
' ' + sync_db + ' < ' + bak_file
|
||||
mw.execShell(my_import_cmd)
|
||||
|
||||
db.query("start slave")
|
||||
pinfo = parseSlaveSyncCmd(data['cmd'])
|
||||
# print(pinfo)
|
||||
if 'Connection_name' in pinfo:
|
||||
db.query("start slave '{}'".format(pinfo['Connection_name']))
|
||||
else:
|
||||
db.query("start slave")
|
||||
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
os.system("rm -rf " + bak_file)
|
||||
|
||||
if os.path.exists(bak_file):
|
||||
os.system("rm -rf " + bak_file)
|
||||
return True
|
||||
|
||||
|
||||
def doFullSyncSSH(version=''):
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
id_rsa_conn = pSqliteDb('slave_id_rsa')
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
if sync_sign != '':
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt"
|
||||
id_rsa = data['id_rsa'].replace('\\n', '\n')
|
||||
@@ -2498,7 +2579,6 @@ def doFullSyncSSH(version=''):
|
||||
return 'fail'
|
||||
|
||||
try:
|
||||
# ssh.load_system_host_keys()
|
||||
mw.execShell("chmod 600 " + SSH_PRIVATE_KEY)
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
@@ -2516,7 +2596,7 @@ def doFullSyncSSH(version=''):
|
||||
|
||||
writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5})
|
||||
dbname = args['db']
|
||||
cmd = "cd /www/server/mdserver-web && python3 plugins/mariadb/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
cmd = "cd /www/server/mdserver-web && source bin/activate && python3 plugins/mariadb/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
print(cmd)
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
@@ -2539,13 +2619,19 @@ def doFullSyncSSH(version=''):
|
||||
if copy_status == None:
|
||||
writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40})
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mariadb/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mariadb/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
|
||||
if result == '':
|
||||
writeDbSyncStatus({'code': 1, 'msg': '同步命令获取失败!', 'progress': 100})
|
||||
return 'fail'
|
||||
|
||||
cmd_data = json.loads(result)
|
||||
|
||||
db.query('stop slave')
|
||||
db.query('stop all slaves')
|
||||
writeDbSyncStatus({'code': 3, 'msg': '停止从库完成...', 'progress': 45})
|
||||
|
||||
cmd = cmd_data['data']['cmd']
|
||||
@@ -2578,6 +2664,7 @@ def doFullSyncSSH(version=''):
|
||||
return 'fail'
|
||||
|
||||
db.query("start slave")
|
||||
db.query("start all slaves")
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
@@ -2585,38 +2672,6 @@ def doFullSyncSSH(version=''):
|
||||
return True
|
||||
|
||||
|
||||
def fullSync(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db', 'begin'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
status_file = '/tmp/db_async_status.txt'
|
||||
if args['begin'] == '1':
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + \
|
||||
getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + args['db'] + '"} &'
|
||||
print(cmd)
|
||||
mw.execShell(cmd)
|
||||
return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0})
|
||||
|
||||
if os.path.exists(status_file):
|
||||
c = mw.readFile(status_file)
|
||||
tmp = json.loads(c)
|
||||
if tmp['code'] == 1:
|
||||
sys_dump_sql = "/tmp/dump.sql"
|
||||
if os.path.exists(sys_dump_sql):
|
||||
dump_size = os.path.getsize(sys_dump_sql)
|
||||
tmp['msg'] = tmp['msg'] + ":" + "同步文件:" + mw.toSize(dump_size)
|
||||
c = json.dumps(tmp)
|
||||
|
||||
# if tmp['code'] == 6:
|
||||
# os.remove(status_file)
|
||||
return c
|
||||
|
||||
return json.dumps({'code': 0, 'msg': '点击开始,开始同步!', 'progress': 0})
|
||||
|
||||
|
||||
def installPreInspection(version):
|
||||
swap_path = mw.getServerDir() + "/swap"
|
||||
if not os.path.exists(swap_path):
|
||||
|
||||
+178
-86
@@ -431,7 +431,6 @@ function syncToDatabase(type){
|
||||
var postData = 'type='+type+'&ids='+JSON.stringify(data);
|
||||
myPost('sync_to_databases', postData, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
// console.log(rdata);
|
||||
showMsg(rdata.msg,function(){
|
||||
dbList();
|
||||
},{ icon: rdata.status ? 1 : 2 });
|
||||
@@ -439,18 +438,6 @@ function syncToDatabase(type){
|
||||
}
|
||||
|
||||
function setRootPwd(type, pwd){
|
||||
if (type==1){
|
||||
var password = $("#MyPassword").val();
|
||||
myPost('set_root_pwd', {password:password}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
dbList();
|
||||
$('.layui-layer-close1').click();
|
||||
},{icon: rdata.status ? 1 : 2});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var index = layer.open({
|
||||
type: 1,
|
||||
area: '500px',
|
||||
@@ -467,8 +454,16 @@ function setRootPwd(type, pwd){
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
yes:function(){
|
||||
setRootPwd(1);
|
||||
yes:function(index,layero){
|
||||
var password = $("#MyPassword").val();
|
||||
myPost('set_root_pwd', {password:password}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata.msg,function(){
|
||||
dbList();
|
||||
layer.close(index);
|
||||
},{icon: rdata.status ? 1 : 2});
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -490,7 +485,6 @@ function showHidePass(obj){
|
||||
function checkSelect(){
|
||||
setTimeout(function () {
|
||||
var num = $('input[type="checkbox"].check:checked').length;
|
||||
// console.log(num);
|
||||
if (num == 1) {
|
||||
$('button[batch="true"]').hide();
|
||||
$('button[batch="false"]').show();
|
||||
@@ -861,7 +855,6 @@ function downloadBackup(file){
|
||||
|
||||
function importBackup(file,name){
|
||||
myPost('import_db_backup',{file:file,name:name}, function(data){
|
||||
// console.log(data);
|
||||
layer.msg('执行成功!');
|
||||
});
|
||||
}
|
||||
@@ -1619,7 +1612,6 @@ function getMasterRepSlaveList(){
|
||||
_data['page'] = page;
|
||||
_data['page_size'] = 10;
|
||||
myPost('get_master_rep_slave_list', _data, function(data){
|
||||
// console.log(data);
|
||||
var rdata = [];
|
||||
try {
|
||||
rdata = $.parseJSON(data.data);
|
||||
@@ -1672,12 +1664,12 @@ function getMasterRepSlaveListPage(){
|
||||
}
|
||||
|
||||
|
||||
function deleteSlave(){
|
||||
myPost('delete_slave', {}, function(data){
|
||||
function deleteSlave(sign = ''){
|
||||
myPost('delete_slave', {sign:sign}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata['msg'], function(){
|
||||
masterOrSlaveConf();
|
||||
},{},3000);
|
||||
},{icon:rdata.status?1:2,time:3000},3000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1685,28 +1677,72 @@ function deleteSlave(){
|
||||
function getFullSyncStatus(db){
|
||||
var timeId = null;
|
||||
|
||||
var btn = '<div class="table_toolbar" style="left:0px;"><span data-status="init" class="sync btn btn-default btn-sm" id="begin_full_sync" title="">开始</span></div>';
|
||||
var loadOpen = layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
"+btn+"\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
myPost('get_slave_list', {page:1,page_size:100}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var rsource = rdata.data;
|
||||
|
||||
if (db == 'ALL' && rsource.length>1){
|
||||
layer.msg("多主不支持该模式!",{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
var dataSource = '';
|
||||
if (rsource.length>1){
|
||||
var sourceList = '';
|
||||
for (var i = 0; i < rsource.length; i++) {
|
||||
if ('Connection_name' in rsource[i]){
|
||||
sourceList += '<option val="'+rsource[i]['Master_Host']+'">'+rsource[i]['Master_Host']+'</option>';
|
||||
}
|
||||
}
|
||||
|
||||
dataSource = "<p class='line' style='text-align:center;'>\
|
||||
<span>同步数据源:</span>\
|
||||
<select class='bt-input-text' name='data_source' style='width:200px;'>" + sourceList + "</select>\
|
||||
</p>";
|
||||
}
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
"+dataSource+"\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='table_toolbar' style='left:0px;'>\
|
||||
<span data-status='init' class='sync btn btn-default btn-sm' id='begin_full_sync'>开始</span>\
|
||||
</div>\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
},
|
||||
success:function(){
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).data('status');
|
||||
var sign = '';
|
||||
if (dataSource !=''){
|
||||
sign = $('select[name="data_source"]').val();
|
||||
}
|
||||
if (val == 'init'){
|
||||
fullSync(db, sign, 1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,sign,0);
|
||||
}, 1000);
|
||||
$(this).data('status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..",{icon:0});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function fullSync(db,begin){
|
||||
|
||||
myPostN('full_sync', {db:db,begin:begin}, function(data){
|
||||
function fullSync(db, sign, begin){
|
||||
myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
$('#full_msg').text(rdata['msg']);
|
||||
$('.progress-bar').css('width',rdata['progress']+'%');
|
||||
@@ -1715,23 +1751,11 @@ function getFullSyncStatus(db){
|
||||
if (rdata['code']==6 ||rdata['code']<0){
|
||||
layer.msg(rdata['msg']);
|
||||
clearInterval(timeId);
|
||||
$("#begin_full_sync").attr('data-status','init');
|
||||
$("#begin_full_sync").data('status','init');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).attr('data-status');
|
||||
if (val == 'init'){
|
||||
fullSync(db,1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,0);
|
||||
}, 1000);
|
||||
$(this).attr('data-status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..");
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function addSlaveSSH(ip=''){
|
||||
@@ -2077,7 +2101,7 @@ function getSlaveUserList(){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: '同步账户列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2101,7 +2125,7 @@ function getSlaveSSHList(page=1){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: 'SSH列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2142,11 +2166,15 @@ function handlerRun(){
|
||||
function initSlaveStatus(){
|
||||
myPost('init_slave_status', '', function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
if (!rdata.status ){
|
||||
layer.msg(rdata.msg,{icon:2,time:10000});
|
||||
return;
|
||||
}
|
||||
showMsg(rdata.msg,function(){
|
||||
if (rdata.status){
|
||||
masterOrSlaveConf();
|
||||
}
|
||||
},{icon:rdata.status?1:2},2000);
|
||||
},{icon:1},2000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2204,33 +2232,48 @@ function masterOrSlaveConf(version=''){
|
||||
}
|
||||
|
||||
_data['page'] = page;
|
||||
_data['page_size'] = 10;
|
||||
_data['page_size'] = 100;
|
||||
|
||||
myPost('get_slave_list', _data, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var list = '';
|
||||
|
||||
var isHasSign = false;
|
||||
for(i in rdata.data){
|
||||
|
||||
var v = rdata.data[i];
|
||||
var status = "<a class='btlink db_error'>异常</>";
|
||||
if ('Connection_name' in v){
|
||||
isHasSign = true;
|
||||
}
|
||||
|
||||
var status = "<a data-id="+i+" class='btlink db_error'>异常</>";
|
||||
if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){
|
||||
status = "正常";
|
||||
}
|
||||
|
||||
list += '<tr>';
|
||||
list += '<td>' + rdata.data[i]['Master_Host'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Master_Port'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Master_User'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Master_Log_File'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_IO_Running'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_SQL_Running'] +'</td>';
|
||||
list += '<td>' + v['Master_Host'] +'</td>';
|
||||
list += '<td>' + v['Master_Port'] +'</td>';
|
||||
list += '<td>' + v['Master_User'] +'</td>';
|
||||
list += '<td>' + v['Master_Log_File'] +'</td>';
|
||||
list += '<td>' + v['Slave_IO_Running'] +'</td>';
|
||||
list += '<td>' + v['Slave_SQL_Running'] +'</td>';
|
||||
if (isHasSign){
|
||||
list += '<td>' + v['Connection_name'] +'</td>';
|
||||
}
|
||||
|
||||
list += '<td>' + status +'</td>';
|
||||
list += '<td style="text-align:right">' +
|
||||
'<a href="javascript:;" class="btlink" onclick="deleteSlave()" title="删除">删除</a>' +
|
||||
'</td>';
|
||||
list += '<td style="text-align:right">\
|
||||
<a data-id="'+i+'" href="javascript:;" class="btlink btn_delete_slave" title="删除">删除</a>\
|
||||
</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
var signThead_th = '';
|
||||
if (isHasSign){
|
||||
var signThead_th = '<th>标识</th>';
|
||||
}
|
||||
|
||||
var con = '<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="DataBody" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
@@ -2241,6 +2284,7 @@ function masterOrSlaveConf(version=''){
|
||||
<th>日志</th>\
|
||||
<th>IO</th>\
|
||||
<th>SQL</th>\
|
||||
'+signThead_th+'\
|
||||
<th>状态</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody>\
|
||||
@@ -2255,22 +2299,75 @@ function masterOrSlaveConf(version=''){
|
||||
// </div>
|
||||
$(".table_slave_status_list").html(con);
|
||||
|
||||
|
||||
$(".btn_delete_slave").click(function(){
|
||||
var id = $(this).data('id');
|
||||
var v = rdata.data[id];
|
||||
if ('Connection_name' in v){
|
||||
deleteSlave(v['Connection_name']);
|
||||
} else{
|
||||
deleteSlave();
|
||||
}
|
||||
});
|
||||
|
||||
$('.db_error').click(function(){
|
||||
var id = $(this).data('id');
|
||||
var info = rdata.data[id];
|
||||
|
||||
var err_line = "";
|
||||
err_line +="<tr>\
|
||||
<td>IO错误</td>\
|
||||
<td>"+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"</td>\
|
||||
</tr>";
|
||||
err_line +="<tr>\
|
||||
<td>SQL错误</td>\
|
||||
<td>"+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"</td>\
|
||||
</tr>";
|
||||
|
||||
err_line +="<tr>\
|
||||
<td>状态</td>\
|
||||
<td>"+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"</td>\
|
||||
</tr>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '同步异常信息',
|
||||
area: '500px',
|
||||
content:"<form class='bt-form pd20 pb70'>\
|
||||
<div class='line'>"+v['Error']+"</div>\
|
||||
<div class='bt-form-submit-btn'>\
|
||||
<button type='button' class='btn btn-success btn-sm btn-title class-copy-db-err'>复制</button>\
|
||||
area: ['600px','300px'],
|
||||
btn:['复制错误',"取消"],
|
||||
content:"<form class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div class='tablescroll'>\
|
||||
<table class='table table-hover' width='100%' cellspacing='0' cellpadding='0' border='0' style='border: 0 none;'>\
|
||||
<thead><tr>\
|
||||
<th style='width:80px;'>类型</th>\
|
||||
<th>内容</th>\
|
||||
</tr></thead>\
|
||||
<tbody>"+ err_line +"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
</form>",
|
||||
success:function(){
|
||||
copyText(v['Error']);
|
||||
$('.class-copy-db-err').click(function(){
|
||||
copyText(v['Error']);
|
||||
});
|
||||
// copyText(v['Error']);
|
||||
// $('.class-copy-db-err').click(function(){
|
||||
// copyText(v['Error']);
|
||||
// });
|
||||
},
|
||||
yes:function(){
|
||||
if (info['Last_IO_Error'] != ''){
|
||||
copyText(info['Last_IO_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Last_SQL_Error'] != ''){
|
||||
copyText(info['Last_SQL_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Slave_SQL_Running_State'] != ''){
|
||||
copyText(info['Slave_SQL_Running_State']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2320,14 +2417,12 @@ function masterOrSlaveConf(version=''){
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
function getMasterStatus(){
|
||||
myPost('get_master_status', '', function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
// console.log('mode:',rdata.data);
|
||||
if ( typeof(rdata.status) != 'undefined' && !rdata.status && rdata.data == 'pwd'){
|
||||
layer.msg(rdata.msg, {icon:2});
|
||||
layer.msg(rdata.msg, {icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2409,7 +2504,6 @@ function masterOrSlaveConf(version=''){
|
||||
return false;
|
||||
},
|
||||
change:function(index,mode,reload){
|
||||
console.log(index,mode,reload);
|
||||
myPost('set_dbrun_mode',{'mode':mode,'reload':reload},function(data){
|
||||
layer.close(index);
|
||||
var rdata = $.parseJSON(data.data);
|
||||
@@ -2425,10 +2519,8 @@ function masterOrSlaveConf(version=''){
|
||||
getMasterDbList();
|
||||
}
|
||||
|
||||
// if (rdata.slave_status){
|
||||
getAsyncMasterDbList();
|
||||
getAsyncDataList()
|
||||
// }
|
||||
getAsyncMasterDbList();
|
||||
getAsyncDataList()
|
||||
});
|
||||
}
|
||||
getMasterStatus();
|
||||
|
||||
@@ -71,10 +71,19 @@ Install_app()
|
||||
if [ ! -d ${mariadbDir}/mariadb-${MY_VER} ];then
|
||||
cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz
|
||||
fi
|
||||
|
||||
INSTALL_CMD=cmake
|
||||
# check cmake version
|
||||
CMAKE_VERSION=`cmake -version | grep version | awk '{print $3}' | awk -F '.' '{print $1}'`
|
||||
if [ "$CMAKE_VERSION" -eq "2" ];then
|
||||
mkdir -p /var/log/mariadb
|
||||
touch /var/log/mariadb/mariadb.log
|
||||
INSTALL_CMD=cmake3
|
||||
fi
|
||||
|
||||
|
||||
if [ ! -d $serverPath/mariadb ];then
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && cmake \
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && ${INSTALL_CMD} \
|
||||
-DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \
|
||||
-DMYSQL_DATADIR=$serverPath/mariadb/data/ \
|
||||
-DMYSQL_USER=mysql \
|
||||
|
||||
@@ -73,8 +73,17 @@ Install_app()
|
||||
fi
|
||||
|
||||
|
||||
INSTALL_CMD=cmake
|
||||
# check cmake version
|
||||
CMAKE_VERSION=`cmake -version | grep version | awk '{print $3}' | awk -F '.' '{print $1}'`
|
||||
if [ "$CMAKE_VERSION" -eq "2" ];then
|
||||
mkdir -p /var/log/mariadb
|
||||
touch /var/log/mariadb/mariadb.log
|
||||
INSTALL_CMD=cmake3
|
||||
fi
|
||||
|
||||
if [ ! -d $serverPath/mariadb ];then
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && cmake \
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && ${INSTALL_CMD} \
|
||||
-DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \
|
||||
-DMYSQL_DATADIR=$serverPath/mariadb/data/ \
|
||||
-DMYSQL_USER=mysql \
|
||||
|
||||
@@ -72,9 +72,17 @@ Install_app()
|
||||
cd ${mariadbDir} && tar -zxvf ${mariadbDir}/mariadb-${MY_VER}.tar.gz
|
||||
fi
|
||||
|
||||
INSTALL_CMD=cmake
|
||||
# check cmake version
|
||||
CMAKE_VERSION=`cmake -version | grep version | awk '{print $3}' | awk -F '.' '{print $1}'`
|
||||
if [ "$CMAKE_VERSION" -eq "2" ];then
|
||||
mkdir -p /var/log/mariadb
|
||||
touch /var/log/mariadb/mariadb.log
|
||||
INSTALL_CMD=cmake3
|
||||
fi
|
||||
|
||||
if [ ! -d $serverPath/mariadb ];then
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && cmake \
|
||||
cd ${mariadbDir}/mariadb-${MY_VER} && ${INSTALL_CMD} \
|
||||
-DCMAKE_INSTALL_PREFIX=$serverPath/mariadb \
|
||||
-DMYSQL_DATADIR=$serverPath/mariadb/data/ \
|
||||
-DMYSQL_USER=mysql \
|
||||
|
||||
@@ -14,6 +14,10 @@ if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings('ignore', category=DeprecationWarning)
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'memcached'
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ port = 33206
|
||||
socket = {$SERVER_APP_PATH}/mysql.sock
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
language={$SERVER_APP_PATH}/bin/usr/share/mysql/english
|
||||
|
||||
@@ -45,7 +48,6 @@ skip-ssl
|
||||
|
||||
log-bin=mysql-bin
|
||||
binlog_format=mixed
|
||||
server-id = 1
|
||||
slow_query_log=1
|
||||
slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log
|
||||
long_query_time=3
|
||||
@@ -71,6 +73,9 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
|
||||
@@ -16,6 +16,9 @@ mysqlx_port = 33260
|
||||
socket = {$SERVER_APP_PATH}/mysql.sock
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
key_buffer_size = 8M
|
||||
@@ -43,7 +46,6 @@ max_allowed_packet = 128M
|
||||
|
||||
log-bin=mysql-bin
|
||||
binlog_format=mixed
|
||||
server-id = 1
|
||||
slow_query_log=1
|
||||
slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log
|
||||
long_query_time=3
|
||||
@@ -68,6 +70,9 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<p onclick="dbList()">管理列表</p>
|
||||
<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="bt-w-con pd15" style="height:555px;overflow: auto;">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+214
-140
@@ -28,6 +28,10 @@ def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getSPluginDir():
|
||||
return '/www/server/mdserver-web/plugins/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
@@ -116,6 +120,10 @@ def contentReplace(content):
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$SERVER_APP_PATH}',
|
||||
service_path + '/' + getPluginName())
|
||||
|
||||
server_id = int(time.time())
|
||||
content = content.replace('{$SERVER_ID}', str(server_id))
|
||||
|
||||
return content
|
||||
|
||||
|
||||
@@ -161,6 +169,10 @@ def pMysqlDb():
|
||||
|
||||
def initDreplace(version=''):
|
||||
|
||||
t = getServerDir()
|
||||
if not os.path.exists(t):
|
||||
return
|
||||
|
||||
conf_dir = getServerDir() + '/etc'
|
||||
mode_dir = conf_dir + '/mode'
|
||||
|
||||
@@ -654,15 +666,15 @@ def isSqlError(mysqlMsg):
|
||||
return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)")
|
||||
if "using password:" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!')
|
||||
if "1045" in mysqlMsg:
|
||||
if "1045," in mysqlMsg:
|
||||
return mw.returnJson(False, '连接错误!')
|
||||
if "SQL syntax" in mysqlMsg:
|
||||
return mw.returnJson(False, 'SQL语法错误!')
|
||||
if "Connection refused" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!')
|
||||
if "1133" in mysqlMsg:
|
||||
if "1133," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库用户不存在!')
|
||||
if "1007" in mysqlMsg:
|
||||
if "1007," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库已经存在!')
|
||||
return None
|
||||
|
||||
@@ -1885,27 +1897,34 @@ def getMasterRepSlaveUserCmd(version):
|
||||
|
||||
mode = recognizeDbMode()
|
||||
|
||||
sid = getDbServerId()
|
||||
channel_name = ""
|
||||
if sid != '':
|
||||
channel_name = " for channel 'r{}';".format(sid)
|
||||
|
||||
if mode == "gtid":
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1" + channel_name
|
||||
if version == '8.0':
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_AUTO_POSITION=1" + channel_name
|
||||
else:
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
if version == "8.0":
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', SOURCE_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',SOURCE_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',SOURCE_LOG_POS=" + \
|
||||
str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
data = {}
|
||||
data['cmd'] = sql
|
||||
@@ -2217,7 +2236,7 @@ def getSlaveSyncCmd(version=''):
|
||||
|
||||
root = mw.getRunDir()
|
||||
cmd = 'cd ' + root + ' && python3 ' + root + \
|
||||
'/plugins/mysql/index.py do_full_sync {"db":"all"}'
|
||||
'/plugins/mysql/index.py do_full_sync {"db":"all","sign":""}'
|
||||
return mw.returnJson(True, 'ok', cmd)
|
||||
|
||||
|
||||
@@ -2233,100 +2252,151 @@ def initSlaveStatus(version=''):
|
||||
return initSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def parseSlaveSyncCmd(cmd):
|
||||
a = {}
|
||||
if cmd.lower().find('for') > 0:
|
||||
cmd_tmp = cmd.split('for')
|
||||
cmd = cmd_tmp[0].strip()
|
||||
|
||||
pattern_c = r"channel \'(.*)\';"
|
||||
match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I)
|
||||
if match_val:
|
||||
m_groups = match_val.groups()
|
||||
a['channel'] = m_groups[0]
|
||||
vlist = cmd.split(',')
|
||||
for i in vlist:
|
||||
tmp = i.strip()
|
||||
tmp_a = tmp.split(" ")
|
||||
real_tmp = tmp_a[len(tmp_a) - 1]
|
||||
kv = real_tmp.split("=")
|
||||
a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '')
|
||||
return a
|
||||
|
||||
|
||||
def initSlaveStatusSyncUser(version=''):
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) < 1:
|
||||
slave_data = conn.field('ip,port,user,pass,mode,cmd').select()
|
||||
if len(slave_data) < 1:
|
||||
return mw.returnJson(False, '需要先添加同步用户配置!')
|
||||
|
||||
# print(data)
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
u = data
|
||||
|
||||
mode_name = 'classic'
|
||||
if u['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
pdb = pMysqlDb()
|
||||
if len(slave_data) == 1:
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
msg = ''
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != mode_name:
|
||||
return mw.returnJson(False, '同步模式不一致!')
|
||||
for x in range(len(slave_data)):
|
||||
slave_t = slave_data[x]
|
||||
mode_name = 'classic'
|
||||
base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \
|
||||
slave_t['port'] + ",USER:" + slave_t['user']
|
||||
|
||||
t = db.query(u['cmd'])
|
||||
# print(t)
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['user'], u['pass']))
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
if slave_t['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
|
||||
if local_mode != mode_name:
|
||||
msg += base_t + '->同步模式不一致'
|
||||
continue
|
||||
|
||||
cmd_sql = slave_t['cmd']
|
||||
if cmd_sql == '':
|
||||
msg += base_t + '->同步命令不能为空'
|
||||
continue
|
||||
|
||||
try:
|
||||
pinfo = parseSlaveSyncCmd(cmd_sql)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, base_t + '->CMD同步命令不合规范!')
|
||||
t = pdb.query(cmd_sql)
|
||||
isError = isSqlError(t)
|
||||
if isError:
|
||||
return isError
|
||||
|
||||
# pdb.query("start slave user='{}' password='{}';".format(
|
||||
# u['user'], u['pass']))
|
||||
|
||||
pdb.query("start slave")
|
||||
pdb.query("start all slaves")
|
||||
|
||||
if msg == '':
|
||||
msg = '初始化成功!'
|
||||
return mw.returnJson(True, msg)
|
||||
|
||||
|
||||
def initSlaveStatusSSH(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,port,id_rsa').find()
|
||||
ssh_list = conn.field('ip,port,id_rsa,db_user').select()
|
||||
|
||||
if len(data) < 1:
|
||||
if len(ssh_list) < 1:
|
||||
return mw.returnJson(False, '需要先配置【[主]SSH配置】!')
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh.txt"
|
||||
ip = data['ip']
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
local_mode = recognizeDbMode()
|
||||
|
||||
import paramiko
|
||||
paramiko.util.log_to_file('paramiko.log')
|
||||
ssh = paramiko.SSHClient()
|
||||
|
||||
try:
|
||||
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
for data in ssh_list:
|
||||
ip = data['ip']
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt"
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
mw.execShell("chmod 600 " + SSH_PRIVATE_KEY)
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
try:
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
cmd_data = json.loads(result)
|
||||
db_user = data['db_user']
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \
|
||||
getSPluginDir() + \
|
||||
'/index.py get_master_rep_slave_user_cmd {"username":"' + \
|
||||
db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
if result.strip() == "":
|
||||
return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!')
|
||||
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主]:' + cmd_data['msg'])
|
||||
cmd_data = json.loads(result)
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg'])
|
||||
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '主【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
|
||||
u = cmd_data['data']['info']
|
||||
ps = u['username'] + "|" + u['password']
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
u = cmd_data['data']['info']
|
||||
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
ps = u['username'] + "|" + u['password']
|
||||
print(ps)
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['username'], u['password']))
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, 'SSH认证配置连接失败!' + str(e))
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
ssh.close()
|
||||
time.sleep(1)
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
ssh.close()
|
||||
if os.path.exists(SSH_PRIVATE_KEY):
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e))
|
||||
db.query('start slave')
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
|
||||
|
||||
@@ -2336,60 +2406,37 @@ def setSlaveStatus(version=''):
|
||||
return mw.returnJson(False, '需要先设置同步配置')
|
||||
|
||||
mode = mw.readFile(mode_file)
|
||||
if mode == 'ssh':
|
||||
return setSlaveStatusSSH(version)
|
||||
if mode == 'sync-user':
|
||||
return setSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def setSlaveStatusSyncUser(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
pdb = pMysqlDb()
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
for v in dlist:
|
||||
connection_name = ''
|
||||
cmd = "slave"
|
||||
if 'Channel_Name' in v:
|
||||
ch_name = v['Channel_Name']
|
||||
cmd = "slave for channel '{}'".format(ch_name)
|
||||
|
||||
db.query("start slave")
|
||||
# db.query("start slave user='{}' password='{}';".format(user, apass))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def setSlaveStatusSSH(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加主服务命令或者执行[初始化]!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,ps').where("ip=?", (ip,)).find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
u = data['ps'].split("|")
|
||||
db.query("start slave user='{}' password='{}';".format(u[0], u[1]))
|
||||
if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'):
|
||||
pdb.query("stop {}".format(cmd))
|
||||
else:
|
||||
pdb.query("start {}".format(cmd))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def deleteSlave(version=''):
|
||||
args = getArgs()
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('stop slave')
|
||||
dlist = db.query('reset slave all')
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
db.query("stop slave for channel '{}'".format(sign))
|
||||
db.query("reset slave all for channel '{}'".format(sign))
|
||||
else:
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
|
||||
@@ -2425,11 +2472,13 @@ def dumpMysqlData(version=''):
|
||||
|
||||
############### --- 重要 同步---- ###########
|
||||
|
||||
def asyncTmpfile():
|
||||
path = '/tmp/mysql_apt_async_status.txt'
|
||||
return path
|
||||
|
||||
|
||||
def writeDbSyncStatus(data):
|
||||
path = '/tmp/db_async_status.txt'
|
||||
# status_data['code'] = 1
|
||||
# status_data['msg'] = '主服务器备份完成...'
|
||||
# status_data['progress'] = 30
|
||||
path = asyncTmpfile()
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
@@ -2447,16 +2496,22 @@ def doFullSync(version=''):
|
||||
|
||||
def doFullSyncUser(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if sync_sign != '':
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
port = data['port']
|
||||
@@ -2473,16 +2528,17 @@ def doFullSyncUser(version=''):
|
||||
writeDbSyncStatus({'code': 1, 'msg': '远程导出数据...', 'progress': 20})
|
||||
|
||||
if not os.path.exists(bak_file):
|
||||
dump_sql_data = getServerDir() + "/bin/mysqldump " + dmp_option + " --force --opt --default-character-set=utf8 --single-transaction -h" + ip + " -P" + \
|
||||
port + " -u" + user + " -p" + apass + \
|
||||
" --ssl-mode=DISABLED " + sync_db + " > " + bak_file
|
||||
dump_sql_data = getServerDir() + "/bin/usr/bin/mysqldump " + dmp_option + " --force --opt --default-character-set=utf8 --single-transaction -h" + ip + " -P" + \
|
||||
port + " -u" + user + " -p\"" + apass + \
|
||||
"\" --ssl-mode=DISABLED " + sync_db + " > " + bak_file
|
||||
# print(dump_sql_data)
|
||||
mw.execShell(dump_sql_data)
|
||||
|
||||
writeDbSyncStatus({'code': 2, 'msg': '本地导入数据...', 'progress': 40})
|
||||
if os.path.exists(bak_file):
|
||||
pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')
|
||||
sock = getSocketFile()
|
||||
my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \
|
||||
my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \
|
||||
' ' + sync_db + ' < ' + bak_file
|
||||
mw.execShell(my_import_cmd)
|
||||
|
||||
@@ -2492,21 +2548,30 @@ def doFullSyncUser(version=''):
|
||||
db.query("start slave")
|
||||
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
os.system("rm -rf " + bak_file)
|
||||
|
||||
if os.path.exists(bak_file):
|
||||
os.system("rm -rf " + bak_file)
|
||||
return True
|
||||
|
||||
|
||||
def doFullSyncSSH(version=''):
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
id_rsa_conn = pSqliteDb('slave_id_rsa')
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
if sync_sign != '':
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt"
|
||||
id_rsa = data['id_rsa'].replace('\\n', '\n')
|
||||
@@ -2548,7 +2613,8 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5})
|
||||
|
||||
dbname = args['db']
|
||||
cmd = "cd /www/server/mdserver-web && python3 plugins/mysql/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \
|
||||
getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
print(cmd)
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
@@ -2571,7 +2637,10 @@ def doFullSyncSSH(version=''):
|
||||
if copy_status == None:
|
||||
writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40})
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \
|
||||
getSPluginDir() + \
|
||||
'/index.py get_master_rep_slave_user_cmd {"username":"' + \
|
||||
db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
@@ -2583,10 +2652,12 @@ def doFullSyncSSH(version=''):
|
||||
cmd = cmd_data['data']['cmd']
|
||||
# 保证同步IP一致
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*)'", "SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*)'", "SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
db.query(cmd)
|
||||
uinfo = cmd_data['data']['info']
|
||||
@@ -2598,8 +2669,10 @@ def doFullSyncSSH(version=''):
|
||||
root_dir = getServerDir()
|
||||
msock = root_dir + "/mysql.sock"
|
||||
mw.execShell("cd /tmp && gzip -d dump.sql.gz")
|
||||
cmd = root_dir + "/bin/mysql -S " + msock + \
|
||||
cmd = root_dir + "/bin/usr/bin/mysql -S " + msock + \
|
||||
" -uroot -p" + pwd + " < /tmp/dump.sql"
|
||||
|
||||
print(cmd)
|
||||
import_data = mw.execShell(cmd)
|
||||
if import_data[0] == '':
|
||||
print(import_data[1])
|
||||
@@ -2609,8 +2682,9 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100})
|
||||
return 'fail'
|
||||
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
uinfo['username'], uinfo['password']))
|
||||
# "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password'])
|
||||
|
||||
db.query("start slave")
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
@@ -2624,12 +2698,12 @@ def fullSync(version=''):
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
status_file = '/tmp/db_async_status.txt'
|
||||
status_file = asyncTmpfile()
|
||||
if args['begin'] == '1':
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + \
|
||||
getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + args['db'] + '"} &'
|
||||
print(cmd)
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + \
|
||||
args['db'] + '","sign":"' + sign + '"} &'
|
||||
# print(cmd)
|
||||
mw.execShell(cmd)
|
||||
return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0})
|
||||
|
||||
|
||||
@@ -48,7 +48,11 @@ fi
|
||||
sh -x $curPath/versions/$2/install.sh $1
|
||||
|
||||
if [ "${action}" == "install" ];then
|
||||
# #初始化
|
||||
#初始化
|
||||
|
||||
if [ "$?" != "0" ];then
|
||||
exit $?
|
||||
fi
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py start ${type}
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/mysql-apt/index.py initd_install ${type}
|
||||
fi
|
||||
|
||||
@@ -162,34 +162,6 @@ function myPort(){
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
//数据库存储信置
|
||||
function changeMySQLDataPath(act) {
|
||||
if (act != undefined) {
|
||||
layer.confirm(lan.soft.mysql_to_msg, { closeBtn: 2, icon: 3 }, function() {
|
||||
var datadir = $("#datadir").val();
|
||||
var data = 'datadir=' + datadir;
|
||||
var loadT = layer.msg(lan.soft.mysql_to_msg1, { icon: 16, time: 0, shade: [0.3, '#000'] });
|
||||
$.post('/database?action=SetDataDir', data, function(rdata) {
|
||||
layer.close(loadT)
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 });
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
$.post('/database?action=GetMySQLInfo', '', function(rdata) {
|
||||
var LimitCon = '<p class="conf_p">\
|
||||
<input id="datadir" class="phpUploadLimit bt-input-text mr5" style="width:350px;" type="text" value="' + rdata.datadir + '" name="datadir">\
|
||||
<span onclick="ChangePath(\'datadir\')" class="glyphicon glyphicon-folder-open cursor mr20" style="width:auto"></span><button class="btn btn-success btn-sm" onclick="changeMySQLDataPath(1)">' + lan.soft.mysql_to + '</button>\
|
||||
</p>';
|
||||
$(".soft-man-con").html(LimitCon);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//数据库配置状态
|
||||
function myPerfOpt() {
|
||||
//获取MySQL配置
|
||||
@@ -1691,12 +1663,12 @@ function getMasterRepSlaveListPage(){
|
||||
}
|
||||
|
||||
|
||||
function deleteSlave(){
|
||||
myPost('delete_slave', {}, function(data){
|
||||
function deleteSlave(sign){
|
||||
myPost('delete_slave', {sign:sign}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata['msg'], function(){
|
||||
masterOrSlaveConf();
|
||||
},{},3000);
|
||||
},{icon:rdata.status?1:2,time:3000},3000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1704,28 +1676,73 @@ function deleteSlave(){
|
||||
function getFullSyncStatus(db){
|
||||
var timeId = null;
|
||||
|
||||
var btn = '<div class="table_toolbar" style="left:0px;"><span data-status="init" class="sync btn btn-default btn-sm" id="begin_full_sync" title="">开始</span></div>';
|
||||
var loadOpen = layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
"+btn+"\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
myPost('get_slave_list', {page:1,page_size:100}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var rsource = rdata.data;
|
||||
|
||||
if (db == 'ALL' && rsource.length>1){
|
||||
layer.msg("多主不支持该模式!",{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
var dataSource = '';
|
||||
if (rsource.length>1){
|
||||
var sourceList = '';
|
||||
for (var i = 0; i < rsource.length; i++) {
|
||||
if ('Channel_Name' in rsource[i]){
|
||||
sourceList += '<option val="'+rsource[i]['Master_Host']+'">'+rsource[i]['Master_Host']+'</option>';
|
||||
}
|
||||
}
|
||||
|
||||
dataSource = "<p class='line' style='text-align:center;'>\
|
||||
<span>同步数据源:</span>\
|
||||
<select class='bt-input-text' name='data_source' style='width:200px;'>" + sourceList + "</select>\
|
||||
</p>";
|
||||
}
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
"+dataSource+"\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='table_toolbar' style='left:0px;'>\
|
||||
<span data-status='init' class='sync btn btn-default btn-sm' id='begin_full_sync'>开始</span>\
|
||||
</div>\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
},
|
||||
success:function(){
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).data('status');
|
||||
var sign = '';
|
||||
if (dataSource !=''){
|
||||
sign = $('select[name="data_source"]').val();
|
||||
}
|
||||
if (val == 'init'){
|
||||
fullSync(db, sign, 1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,sign,0);
|
||||
}, 1000);
|
||||
$(this).data('status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..",{icon:0});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function fullSync(db,begin){
|
||||
function fullSync(db,sign,begin){
|
||||
|
||||
myPostN('full_sync', {db:db,begin:begin}, function(data){
|
||||
myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
$('#full_msg').text(rdata['msg']);
|
||||
$('.progress-bar').css('width',rdata['progress']+'%');
|
||||
@@ -1734,23 +1751,10 @@ function getFullSyncStatus(db){
|
||||
if (rdata['code']==6 ||rdata['code']<0){
|
||||
layer.msg(rdata['msg']);
|
||||
clearInterval(timeId);
|
||||
$("#begin_full_sync").attr('data-status','init');
|
||||
$("#begin_full_sync").data('data','init');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).attr('data-status');
|
||||
if (val == 'init'){
|
||||
fullSync(db,1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,0);
|
||||
}, 1000);
|
||||
$(this).attr('data-status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addSlaveSSH(ip=''){
|
||||
@@ -1920,18 +1924,29 @@ function addSlaveSyncUser(ip=''){
|
||||
<div class='line'><span class='tname'>同步账户</span><div class='info-r'><input name='user' class='bt-input-text mr5' type='text' style='width:330px;' value='"+user+"'></div></div>\
|
||||
<div class='line'><span class='tname'>同步密码</span><div class='info-r'><input name='pass' class='bt-input-text mr5' type='text' style='width:330px;' value='"+pass+"'></div></div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>CMD[最好填好]</span>\
|
||||
<span class='tname'>CMD[必须填写]</span>\
|
||||
<div class='info-r'><textarea class='bt-input-text mr5' row='20' cols='30' name='cmd' style='width:330px;height:150px;'></textarea></div>\
|
||||
</div>\
|
||||
<input type='hidden' name='mode' value='"+mode+"' />\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('textarea[name="cmd"]').html(cmd);
|
||||
|
||||
$('textarea[name="cmd"]').change(function(){
|
||||
var val = $(this).val();
|
||||
var vlist = val.split(',');
|
||||
var a = {};
|
||||
if (val.toLowerCase().indexOf('for')>0){
|
||||
cmd_tmp = val.split('for');
|
||||
val = cmd_tmp[0].trim();
|
||||
|
||||
const channel_str = cmd_tmp[1].trim();
|
||||
const ch_reg = /channel \'(.*)\';/;
|
||||
var match_val = channel_str.match(ch_reg);
|
||||
if (match_val.length>1){
|
||||
a['channel'] = match_val[1];
|
||||
}
|
||||
}
|
||||
|
||||
var vlist = val.split(',');
|
||||
for (var i in vlist) {
|
||||
var tmp = toTrim(vlist[i]);
|
||||
var tmp_a = tmp.split(" ");
|
||||
@@ -2098,7 +2113,7 @@ function getSlaveUserList(){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: '同步账户列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2122,7 +2137,7 @@ function getSlaveSSHList(page=1){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: 'SSH列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2230,10 +2245,16 @@ function masterOrSlaveConf(version=''){
|
||||
myPost('get_slave_list', _data, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var list = '';
|
||||
|
||||
var isHasSign = false;
|
||||
for(i in rdata.data){
|
||||
|
||||
var v = rdata.data[i];
|
||||
var status = "<a class='btlink db_error'>异常</>";
|
||||
if ('Channel_Name' in v){
|
||||
isHasSign = true;
|
||||
}
|
||||
|
||||
var status = "<a data-id="+i+" class='btlink db_error'>异常</>";
|
||||
if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){
|
||||
status = "正常";
|
||||
}
|
||||
@@ -2245,13 +2266,23 @@ function masterOrSlaveConf(version=''){
|
||||
list += '<td>' + rdata.data[i]['Master_Log_File'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_IO_Running'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_SQL_Running'] +'</td>';
|
||||
|
||||
if (isHasSign){
|
||||
list += '<td>' + v['Channel_Name'] +'</td>';
|
||||
}
|
||||
|
||||
list += '<td>' + status +'</td>';
|
||||
list += '<td style="text-align:right">' +
|
||||
'<a href="javascript:;" class="btlink" onclick="deleteSlave()" title="删除">删除</a>' +
|
||||
'<a data-id="'+i+'" href="javascript:;" class="btlink btn_delete_slave" title="删除">删除</a>' +
|
||||
'</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
var signThead_th = '';
|
||||
if (isHasSign){
|
||||
var signThead_th = '<th>标识</th>';
|
||||
}
|
||||
|
||||
var con = '<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="DataBody" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
@@ -2262,6 +2293,7 @@ function masterOrSlaveConf(version=''){
|
||||
<th>日志</th>\
|
||||
<th>IO</th>\
|
||||
<th>SQL</th>\
|
||||
'+signThead_th+'\
|
||||
<th>状态</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody>\
|
||||
@@ -2276,22 +2308,74 @@ function masterOrSlaveConf(version=''){
|
||||
// </div>
|
||||
$(".table_slave_status_list").html(con);
|
||||
|
||||
$('.db_error').click(function(){
|
||||
$(".btn_delete_slave").click(function(){
|
||||
var id = $(this).data('id');
|
||||
var v = rdata.data[id];
|
||||
if ('Channel_Name' in v){
|
||||
deleteSlave(v['Channel_Name']);
|
||||
} else{
|
||||
deleteSlave();
|
||||
}
|
||||
});
|
||||
|
||||
$('.db_error').click(function(){
|
||||
var id = $(this).data('id');
|
||||
var info = rdata.data[id];
|
||||
|
||||
var err_line = "";
|
||||
err_line +="<tr>\
|
||||
<td>IO错误</td>\
|
||||
<td>"+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"</td>\
|
||||
</tr>";
|
||||
err_line +="<tr>\
|
||||
<td>SQL错误</td>\
|
||||
<td>"+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"</td>\
|
||||
</tr>";
|
||||
|
||||
err_line +="<tr>\
|
||||
<td>状态</td>\
|
||||
<td>"+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"</td>\
|
||||
</tr>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '同步异常信息',
|
||||
area: '500px',
|
||||
content:"<form class='bt-form pd20 pb70'>\
|
||||
<div class='line'>"+v['Error']+"</div>\
|
||||
<div class='bt-form-submit-btn'>\
|
||||
<button type='button' class='btn btn-success btn-sm btn-title class-copy-db-err'>复制</button>\
|
||||
area: ['600px','300px'],
|
||||
btn:['复制错误',"取消"],
|
||||
content:"<form class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div class='tablescroll'>\
|
||||
<table class='table table-hover' width='100%' cellspacing='0' cellpadding='0' border='0' style='border: 0 none;'>\
|
||||
<thead><tr>\
|
||||
<th style='width:80px;'>类型</th>\
|
||||
<th>内容</th>\
|
||||
</tr></thead>\
|
||||
<tbody>"+ err_line +"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
</form>",
|
||||
success:function(){
|
||||
copyText(v['Error']);
|
||||
$('.class-copy-db-err').click(function(){
|
||||
copyText(v['Error']);
|
||||
});
|
||||
// copyText(v['Error']);
|
||||
// $('.class-copy-db-err').click(function(){
|
||||
// copyText(v['Error']);
|
||||
// });
|
||||
},
|
||||
yes:function(){
|
||||
if (info['Last_IO_Error'] != ''){
|
||||
copyText(info['Last_IO_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Last_SQL_Error'] != ''){
|
||||
copyText(info['Last_SQL_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Slave_SQL_Running_State'] != ''){
|
||||
copyText(info['Slave_SQL_Running_State']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,7 +35,22 @@ if [ "$OSNAME" == "ubuntu" ];then
|
||||
VERSION_ID="18.04"
|
||||
fi
|
||||
|
||||
SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_amd64
|
||||
ARCH="amd64"
|
||||
TMP_ARCH=`arch`
|
||||
if [ "$TMP_ARCH" == "x86_64" ];then
|
||||
ARCH="amd64"
|
||||
elif [ "$TMP_ARCH" == "aarch64" ];then
|
||||
ARCH="arm64"
|
||||
else
|
||||
ARCH="amd64"
|
||||
fi
|
||||
|
||||
if [ "$ARCH" != "amd64" ];then
|
||||
echo "暂时不支持该${ARCH}" > $install_tmp
|
||||
exit 0
|
||||
fi
|
||||
|
||||
SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH}
|
||||
|
||||
APT_INSTALL()
|
||||
{
|
||||
|
||||
@@ -22,8 +22,25 @@ VERSION_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/mysql-apt && bash install.sh install 8.0
|
||||
|
||||
|
||||
ARCH="amd64"
|
||||
TMP_ARCH=`arch`
|
||||
if [ "$TMP_ARCH" == "x86_64" ];then
|
||||
ARCH="amd64"
|
||||
elif [ "$TMP_ARCH" == "aarch64" ];then
|
||||
ARCH="arm64"
|
||||
else
|
||||
ARCH="amd64"
|
||||
fi
|
||||
|
||||
if [ "$ARCH" != "amd64" ];then
|
||||
echo "暂时不支持该${ARCH}" > $install_tmp
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
MYSQL_VER=8.0.30
|
||||
SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_amd64
|
||||
SUFFIX_NAME=${MYSQL_VER}-1${OSNAME}${VERSION_ID}_${ARCH}
|
||||
|
||||
|
||||
# /lib/systemd/system/mysql.service
|
||||
@@ -81,7 +98,6 @@ Install_mysql()
|
||||
useradd -g mysql mysql
|
||||
fi
|
||||
|
||||
|
||||
isApt=`which apt`
|
||||
if [ "$isApt" != "" ];then
|
||||
APT_INSTALL
|
||||
|
||||
@@ -14,6 +14,9 @@ port = 33206
|
||||
socket = {$SERVER_APP_PATH}/mysql.sock
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
language={$SERVER_APP_PATH}/bin/usr/share/mysql/english
|
||||
|
||||
@@ -46,7 +49,6 @@ skip-ssl
|
||||
|
||||
log-bin=mysql-bin
|
||||
binlog_format=mixed
|
||||
server-id = 1
|
||||
slow_query_log=1
|
||||
slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log
|
||||
long_query_time=3
|
||||
@@ -72,6 +74,9 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
|
||||
@@ -16,6 +16,9 @@ mysqlx_port = 33260
|
||||
socket = {$SERVER_APP_PATH}/mysql.sock
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
key_buffer_size = 8M
|
||||
@@ -43,7 +46,6 @@ max_allowed_packet = 128M
|
||||
|
||||
log-bin=mysql-bin
|
||||
binlog_format=mixed
|
||||
server-id = 1
|
||||
slow_query_log=1
|
||||
slow-query-log-file={$SERVER_APP_PATH}/data/mysql-slow.log
|
||||
long_query_time=3
|
||||
@@ -68,6 +70,9 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<p onclick="dbList()">管理列表</p>
|
||||
<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="bt-w-con pd15" style="height:555px;overflow: auto;">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+219
-152
@@ -36,6 +36,10 @@ def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getSPluginDir():
|
||||
return '/www/server/mdserver-web/plugins/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
@@ -101,6 +105,14 @@ def getDbPort():
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getDbServerId():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
rep = 'server-id\s*=\s*(.*)'
|
||||
tmp = re.search(rep, content)
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getSocketFile():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
@@ -123,6 +135,9 @@ def contentReplace(content):
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$SERVER_APP_PATH}',
|
||||
service_path + '/' + getPluginName())
|
||||
|
||||
server_id = int(time.time())
|
||||
content = content.replace('{$SERVER_ID}', str(server_id))
|
||||
return content
|
||||
|
||||
|
||||
@@ -640,15 +655,15 @@ def isSqlError(mysqlMsg):
|
||||
return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)")
|
||||
if "using password:" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!')
|
||||
if "1045" in mysqlMsg:
|
||||
if "1045," in mysqlMsg:
|
||||
return mw.returnJson(False, '连接错误!')
|
||||
if "SQL syntax" in mysqlMsg:
|
||||
return mw.returnJson(False, 'SQL语法错误!')
|
||||
if "Connection refused" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!')
|
||||
if "1133" in mysqlMsg:
|
||||
if "1133," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库用户不存在!')
|
||||
if "1007" in mysqlMsg:
|
||||
if "1007," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库已经存在!')
|
||||
return None
|
||||
|
||||
@@ -1863,27 +1878,34 @@ def getMasterRepSlaveUserCmd(version):
|
||||
|
||||
mode = recognizeDbMode()
|
||||
|
||||
sid = getDbServerId()
|
||||
channel_name = ""
|
||||
if sid != '':
|
||||
channel_name = " for channel 'r{}';".format(sid)
|
||||
|
||||
if mode == "gtid":
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1" + channel_name
|
||||
if version == '8.0':
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_AUTO_POSITION=1" + channel_name
|
||||
else:
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
if version == "8.0":
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', SOURCE_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',SOURCE_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',SOURCE_LOG_POS=" + \
|
||||
str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
data = {}
|
||||
data['cmd'] = sql
|
||||
@@ -2154,22 +2176,10 @@ def updateSlaveSSH(version=''):
|
||||
|
||||
|
||||
def getSlaveList(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
ret = []
|
||||
for x in range(0, len(dlist)):
|
||||
tmp = {}
|
||||
tmp['Master_User'] = dlist[x]["Master_User"]
|
||||
tmp['Master_Host'] = dlist[x]["Master_Host"]
|
||||
tmp['Master_Port'] = dlist[x]["Master_Port"]
|
||||
tmp['Master_Log_File'] = dlist[x]["Master_Log_File"]
|
||||
tmp['Slave_IO_Running'] = dlist[x]["Slave_IO_Running"]
|
||||
tmp['Slave_SQL_Running'] = dlist[x]["Slave_SQL_Running"]
|
||||
ret.append(tmp)
|
||||
data = {}
|
||||
data['data'] = ret
|
||||
|
||||
data['data'] = dlist
|
||||
return mw.getJson(data)
|
||||
|
||||
|
||||
@@ -2193,100 +2203,149 @@ def initSlaveStatus(version=''):
|
||||
return initSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def parseSlaveSyncCmd(cmd):
|
||||
a = {}
|
||||
if cmd.lower().find('for') > 0:
|
||||
cmd_tmp = cmd.split('for')
|
||||
cmd = cmd_tmp[0].strip()
|
||||
|
||||
pattern_c = r"channel \'(.*)\';"
|
||||
match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I)
|
||||
if match_val:
|
||||
m_groups = match_val.groups()
|
||||
a['channel'] = m_groups[0]
|
||||
vlist = cmd.split(',')
|
||||
for i in vlist:
|
||||
tmp = i.strip()
|
||||
tmp_a = tmp.split(" ")
|
||||
real_tmp = tmp_a[len(tmp_a) - 1]
|
||||
kv = real_tmp.split("=")
|
||||
a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '')
|
||||
return a
|
||||
|
||||
|
||||
def initSlaveStatusSyncUser(version=''):
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) < 1:
|
||||
slave_data = conn.field('ip,port,user,pass,mode,cmd').select()
|
||||
if len(slave_data) < 1:
|
||||
return mw.returnJson(False, '需要先添加同步用户配置!')
|
||||
|
||||
# print(data)
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
u = data
|
||||
|
||||
mode_name = 'classic'
|
||||
if u['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
pdb = pMysqlDb()
|
||||
if len(slave_data) == 1:
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
msg = ''
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != mode_name:
|
||||
return mw.returnJson(False, '同步模式不一致!')
|
||||
for x in range(len(slave_data)):
|
||||
slave_t = slave_data[x]
|
||||
mode_name = 'classic'
|
||||
base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \
|
||||
slave_t['port'] + ",USER:" + slave_t['user']
|
||||
|
||||
t = db.query(u['cmd'])
|
||||
# print(t)
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['user'], u['pass']))
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
if slave_t['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
|
||||
if local_mode != mode_name:
|
||||
msg += base_t + '->同步模式不一致'
|
||||
continue
|
||||
|
||||
cmd_sql = slave_t['cmd']
|
||||
if cmd_sql == '':
|
||||
msg += base_t + '->同步命令不能为空'
|
||||
continue
|
||||
|
||||
try:
|
||||
pinfo = parseSlaveSyncCmd(cmd_sql)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, base_t + '->CMD同步命令不合规范!')
|
||||
# print(u['cmd'])
|
||||
t = pdb.query(cmd_sql)
|
||||
isError = isSqlError(t)
|
||||
if isError:
|
||||
return isError
|
||||
|
||||
# pdb.query("start slave user='{}' password='{}';".format(
|
||||
# u['user'], u['pass']))
|
||||
|
||||
pdb.query("start slave")
|
||||
pdb.query("start all slaves")
|
||||
|
||||
if msg == '':
|
||||
msg = '初始化成功!'
|
||||
return mw.returnJson(True, msg)
|
||||
|
||||
|
||||
def initSlaveStatusSSH(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,port,id_rsa').find()
|
||||
ssh_list = conn.field('ip,port,id_rsa,db_user').select()
|
||||
|
||||
if len(data) < 1:
|
||||
if len(ssh_list) < 1:
|
||||
return mw.returnJson(False, '需要先配置【[主]SSH配置】!')
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh.txt"
|
||||
ip = data['ip']
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
local_mode = recognizeDbMode()
|
||||
|
||||
import paramiko
|
||||
paramiko.util.log_to_file('paramiko.log')
|
||||
ssh = paramiko.SSHClient()
|
||||
|
||||
try:
|
||||
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
for data in ssh_list:
|
||||
ip = data['ip']
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt"
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
mw.execShell("chmod 600 " + SSH_PRIVATE_KEY)
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
try:
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
cmd_data = json.loads(result)
|
||||
db_user = data['db_user']
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql-yum/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
if result.strip() == "":
|
||||
return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!')
|
||||
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主]:' + cmd_data['msg'])
|
||||
cmd_data = json.loads(result)
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg'])
|
||||
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '主【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
|
||||
u = cmd_data['data']['info']
|
||||
ps = u['username'] + "|" + u['password']
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
u = cmd_data['data']['info']
|
||||
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
ps = u['username'] + "|" + u['password']
|
||||
print(ps)
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['username'], u['password']))
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, 'SSH认证配置连接失败!' + str(e))
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
ssh.close()
|
||||
time.sleep(1)
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
ssh.close()
|
||||
if os.path.exists(SSH_PRIVATE_KEY):
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e))
|
||||
db.query('start slave')
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
|
||||
|
||||
@@ -2296,60 +2355,37 @@ def setSlaveStatus(version=''):
|
||||
return mw.returnJson(False, '需要先设置同步配置')
|
||||
|
||||
mode = mw.readFile(mode_file)
|
||||
if mode == 'ssh':
|
||||
return setSlaveStatusSSH(version)
|
||||
if mode == 'sync-user':
|
||||
return setSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def setSlaveStatusSyncUser(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
pdb = pMysqlDb()
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
for v in dlist:
|
||||
connection_name = ''
|
||||
cmd = "slave"
|
||||
if 'Channel_Name' in v:
|
||||
ch_name = v['Channel_Name']
|
||||
cmd = "slave for channel '{}'".format(ch_name)
|
||||
|
||||
db.query("start slave")
|
||||
# db.query("start slave user='{}' password='{}';".format(user, apass))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def setSlaveStatusSSH(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加主服务命令或者执行[初始化]!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,ps').where("ip=?", (ip,)).find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
u = data['ps'].split("|")
|
||||
db.query("start slave user='{}' password='{}';".format(u[0], u[1]))
|
||||
if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'):
|
||||
pdb.query("stop {}".format(cmd))
|
||||
else:
|
||||
pdb.query("start {}".format(cmd))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def deleteSlave(version=''):
|
||||
args = getArgs()
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('stop slave')
|
||||
dlist = db.query('reset slave all')
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
db.query("stop slave for channel '{}'".format(sign))
|
||||
db.query("reset slave all for channel '{}'".format(sign))
|
||||
else:
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
|
||||
@@ -2385,11 +2421,13 @@ def dumpMysqlData(version=''):
|
||||
|
||||
############### --- 重要 同步---- ###########
|
||||
|
||||
def asyncTmpfile():
|
||||
path = '/tmp/mysql_yum_async_status.txt'
|
||||
return path
|
||||
|
||||
|
||||
def writeDbSyncStatus(data):
|
||||
path = '/tmp/db_async_status.txt'
|
||||
# status_data['code'] = 1
|
||||
# status_data['msg'] = '主服务器备份完成...'
|
||||
# status_data['progress'] = 30
|
||||
path = asyncTmpfile()
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
@@ -2407,16 +2445,22 @@ def doFullSync(version=''):
|
||||
|
||||
def doFullSyncUser(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if sync_sign != '':
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
port = data['port']
|
||||
@@ -2433,16 +2477,17 @@ def doFullSyncUser(version=''):
|
||||
writeDbSyncStatus({'code': 1, 'msg': '远程导出数据...', 'progress': 20})
|
||||
|
||||
if not os.path.exists(bak_file):
|
||||
dump_sql_data = getServerDir() + "/bin/mysqldump " + dmp_option + " --force --opt --default-character-set=utf8 --single-transaction -h" + ip + " -P" + \
|
||||
port + " -u" + user + " -p" + apass + \
|
||||
" --ssl-mode=DISABLED " + sync_db + " > " + bak_file
|
||||
dump_sql_data = getServerDir() + "/bin/usr/bin/mysqldump " + dmp_option + " --force --opt --default-character-set=utf8 --single-transaction -h" + ip + " -P" + \
|
||||
port + " -u" + user + " -p\"" + apass + \
|
||||
"\" --ssl-mode=DISABLED " + sync_db + " > " + bak_file
|
||||
# print(dump_sql_data)
|
||||
mw.execShell(dump_sql_data)
|
||||
|
||||
writeDbSyncStatus({'code': 2, 'msg': '本地导入数据...', 'progress': 40})
|
||||
if os.path.exists(bak_file):
|
||||
pwd = pSqliteDb('config').where('id=?', (1,)).getField('mysql_root')
|
||||
sock = getSocketFile()
|
||||
my_import_cmd = getServerDir() + '/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \
|
||||
my_import_cmd = getServerDir() + '/bin/usr/bin/mysql -S ' + sock + ' -uroot -p' + pwd + \
|
||||
' ' + sync_db + ' < ' + bak_file
|
||||
mw.execShell(my_import_cmd)
|
||||
|
||||
@@ -2452,21 +2497,30 @@ def doFullSyncUser(version=''):
|
||||
db.query("start slave")
|
||||
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
os.system("rm -rf " + bak_file)
|
||||
|
||||
if os.path.exists(bak_file):
|
||||
os.system("rm -rf " + bak_file)
|
||||
return True
|
||||
|
||||
|
||||
def doFullSyncSSH(version=''):
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
id_rsa_conn = pSqliteDb('slave_id_rsa')
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
if sync_sign != '':
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt"
|
||||
id_rsa = data['id_rsa'].replace('\\n', '\n')
|
||||
@@ -2508,7 +2562,8 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5})
|
||||
|
||||
dbname = args['db']
|
||||
cmd = "cd /www/server/mdserver-web && python3 plugins/mysql/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \
|
||||
getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
print(cmd)
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
@@ -2531,7 +2586,10 @@ def doFullSyncSSH(version=''):
|
||||
if copy_status == None:
|
||||
writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40})
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \
|
||||
getSPluginDir() + \
|
||||
'/index.py get_master_rep_slave_user_cmd {"username":"' + \
|
||||
db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
@@ -2543,10 +2601,12 @@ def doFullSyncSSH(version=''):
|
||||
cmd = cmd_data['data']['cmd']
|
||||
# 保证同步IP一致
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*)'", "SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*)'", "SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
db.query(cmd)
|
||||
uinfo = cmd_data['data']['info']
|
||||
@@ -2558,8 +2618,10 @@ def doFullSyncSSH(version=''):
|
||||
root_dir = getServerDir()
|
||||
msock = root_dir + "/mysql.sock"
|
||||
mw.execShell("cd /tmp && gzip -d dump.sql.gz")
|
||||
cmd = root_dir + "/bin/mysql -S " + msock + \
|
||||
cmd = root_dir + "/bin/usr/bin/mysql -S " + msock + \
|
||||
" -uroot -p" + pwd + " < /tmp/dump.sql"
|
||||
|
||||
print(cmd)
|
||||
import_data = mw.execShell(cmd)
|
||||
if import_data[0] == '':
|
||||
print(import_data[1])
|
||||
@@ -2569,8 +2631,9 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100})
|
||||
return 'fail'
|
||||
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
uinfo['username'], uinfo['password']))
|
||||
# "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password'])
|
||||
|
||||
db.query("start slave")
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
@@ -2584,12 +2647,16 @@ def fullSync(version=''):
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
status_file = '/tmp/db_async_status.txt'
|
||||
sign = ''
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
|
||||
status_file = asyncTmpfile()
|
||||
if args['begin'] == '1':
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + \
|
||||
getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + args['db'] + '"} &'
|
||||
print(cmd)
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + \
|
||||
args['db'] + '","sign":"' + sign + '"} &'
|
||||
# print(cmd)
|
||||
mw.execShell(cmd)
|
||||
return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0})
|
||||
|
||||
|
||||
@@ -162,34 +162,6 @@ function myPort(){
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
//数据库存储信置
|
||||
function changeMySQLDataPath(act) {
|
||||
if (act != undefined) {
|
||||
layer.confirm(lan.soft.mysql_to_msg, { closeBtn: 2, icon: 3 }, function() {
|
||||
var datadir = $("#datadir").val();
|
||||
var data = 'datadir=' + datadir;
|
||||
var loadT = layer.msg(lan.soft.mysql_to_msg1, { icon: 16, time: 0, shade: [0.3, '#000'] });
|
||||
$.post('/database?action=SetDataDir', data, function(rdata) {
|
||||
layer.close(loadT)
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 });
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
$.post('/database?action=GetMySQLInfo', '', function(rdata) {
|
||||
var LimitCon = '<p class="conf_p">\
|
||||
<input id="datadir" class="phpUploadLimit bt-input-text mr5" style="width:350px;" type="text" value="' + rdata.datadir + '" name="datadir">\
|
||||
<span onclick="ChangePath(\'datadir\')" class="glyphicon glyphicon-folder-open cursor mr20" style="width:auto"></span><button class="btn btn-success btn-sm" onclick="changeMySQLDataPath(1)">' + lan.soft.mysql_to + '</button>\
|
||||
</p>';
|
||||
$(".soft-man-con").html(LimitCon);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//数据库配置状态
|
||||
function myPerfOpt() {
|
||||
//获取MySQL配置
|
||||
@@ -1691,12 +1663,12 @@ function getMasterRepSlaveListPage(){
|
||||
}
|
||||
|
||||
|
||||
function deleteSlave(){
|
||||
myPost('delete_slave', {}, function(data){
|
||||
function deleteSlave(sign){
|
||||
myPost('delete_slave', {sign:sign}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata['msg'], function(){
|
||||
masterOrSlaveConf();
|
||||
},{},3000);
|
||||
},{icon:rdata.status?1:2,time:3000},3000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1704,28 +1676,73 @@ function deleteSlave(){
|
||||
function getFullSyncStatus(db){
|
||||
var timeId = null;
|
||||
|
||||
var btn = '<div class="table_toolbar" style="left:0px;"><span data-status="init" class="sync btn btn-default btn-sm" id="begin_full_sync" title="">开始</span></div>';
|
||||
var loadOpen = layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
"+btn+"\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
myPost('get_slave_list', {page:1,page_size:100}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var rsource = rdata.data;
|
||||
|
||||
if (db == 'ALL' && rsource.length>1){
|
||||
layer.msg("多主不支持该模式!",{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
var dataSource = '';
|
||||
if (rsource.length>1){
|
||||
var sourceList = '';
|
||||
for (var i = 0; i < rsource.length; i++) {
|
||||
if ('Channel_Name' in rsource[i]){
|
||||
sourceList += '<option val="'+rsource[i]['Master_Host']+'">'+rsource[i]['Master_Host']+'</option>';
|
||||
}
|
||||
}
|
||||
|
||||
dataSource = "<p class='line' style='text-align:center;'>\
|
||||
<span>同步数据源:</span>\
|
||||
<select class='bt-input-text' name='data_source' style='width:200px;'>" + sourceList + "</select>\
|
||||
</p>";
|
||||
}
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
"+dataSource+"\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='table_toolbar' style='left:0px;'>\
|
||||
<span data-status='init' class='sync btn btn-default btn-sm' id='begin_full_sync'>开始</span>\
|
||||
</div>\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
},
|
||||
success:function(){
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).data('status');
|
||||
var sign = '';
|
||||
if (dataSource !=''){
|
||||
sign = $('select[name="data_source"]').val();
|
||||
}
|
||||
if (val == 'init'){
|
||||
fullSync(db, sign, 1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,sign,0);
|
||||
}, 1000);
|
||||
$(this).data('status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..",{icon:0});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function fullSync(db,begin){
|
||||
function fullSync(db,sign,begin){
|
||||
|
||||
myPostN('full_sync', {db:db,begin:begin}, function(data){
|
||||
myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
$('#full_msg').text(rdata['msg']);
|
||||
$('.progress-bar').css('width',rdata['progress']+'%');
|
||||
@@ -1738,19 +1755,6 @@ function getFullSyncStatus(db){
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).attr('data-status');
|
||||
if (val == 'init'){
|
||||
fullSync(db,1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,0);
|
||||
}, 1000);
|
||||
$(this).attr('data-status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addSlaveSSH(ip=''){
|
||||
@@ -1920,18 +1924,29 @@ function addSlaveSyncUser(ip=''){
|
||||
<div class='line'><span class='tname'>同步账户</span><div class='info-r'><input name='user' class='bt-input-text mr5' type='text' style='width:330px;' value='"+user+"'></div></div>\
|
||||
<div class='line'><span class='tname'>同步密码</span><div class='info-r'><input name='pass' class='bt-input-text mr5' type='text' style='width:330px;' value='"+pass+"'></div></div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>CMD[最好填好]</span>\
|
||||
<span class='tname'>CMD[必须填写]</span>\
|
||||
<div class='info-r'><textarea class='bt-input-text mr5' row='20' cols='30' name='cmd' style='width:330px;height:150px;'></textarea></div>\
|
||||
</div>\
|
||||
<input type='hidden' name='mode' value='"+mode+"' />\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('textarea[name="cmd"]').html(cmd);
|
||||
|
||||
$('textarea[name="cmd"]').change(function(){
|
||||
var val = $(this).val();
|
||||
var vlist = val.split(',');
|
||||
var a = {};
|
||||
if (val.toLowerCase().indexOf('for')>0){
|
||||
cmd_tmp = val.split('for');
|
||||
val = cmd_tmp[0].trim();
|
||||
|
||||
const channel_str = cmd_tmp[1].trim();
|
||||
const ch_reg = /channel \'(.*)\';/;
|
||||
var match_val = channel_str.match(ch_reg);
|
||||
if (match_val.length>1){
|
||||
a['channel'] = match_val[1];
|
||||
}
|
||||
}
|
||||
|
||||
var vlist = val.split(',');
|
||||
for (var i in vlist) {
|
||||
var tmp = toTrim(vlist[i]);
|
||||
var tmp_a = tmp.split(" ");
|
||||
@@ -2098,7 +2113,7 @@ function getSlaveUserList(){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: '同步账户列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2122,7 +2137,7 @@ function getSlaveSSHList(page=1){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: 'SSH列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2230,10 +2245,16 @@ function masterOrSlaveConf(version=''){
|
||||
myPost('get_slave_list', _data, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var list = '';
|
||||
|
||||
var isHasSign = false;
|
||||
for(i in rdata.data){
|
||||
|
||||
var v = rdata.data[i];
|
||||
var status = "<a class='btlink db_error'>异常</>";
|
||||
if ('Channel_Name' in v){
|
||||
isHasSign = true;
|
||||
}
|
||||
|
||||
var status = "<a data-id="+i+" class='btlink db_error'>异常</>";
|
||||
if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){
|
||||
status = "正常";
|
||||
}
|
||||
@@ -2245,13 +2266,23 @@ function masterOrSlaveConf(version=''){
|
||||
list += '<td>' + rdata.data[i]['Master_Log_File'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_IO_Running'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_SQL_Running'] +'</td>';
|
||||
|
||||
if (isHasSign){
|
||||
list += '<td>' + v['Channel_Name'] +'</td>';
|
||||
}
|
||||
|
||||
list += '<td>' + status +'</td>';
|
||||
list += '<td style="text-align:right">' +
|
||||
'<a href="javascript:;" class="btlink" onclick="deleteSlave()" title="删除">删除</a>' +
|
||||
'<a data-id="'+i+'" href="javascript:;" class="btlink btn_delete_slave" title="删除">删除</a>' +
|
||||
'</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
var signThead_th = '';
|
||||
if (isHasSign){
|
||||
var signThead_th = '<th>标识</th>';
|
||||
}
|
||||
|
||||
var con = '<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="DataBody" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
@@ -2262,6 +2293,7 @@ function masterOrSlaveConf(version=''){
|
||||
<th>日志</th>\
|
||||
<th>IO</th>\
|
||||
<th>SQL</th>\
|
||||
'+signThead_th+'\
|
||||
<th>状态</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody>\
|
||||
@@ -2276,22 +2308,74 @@ function masterOrSlaveConf(version=''){
|
||||
// </div>
|
||||
$(".table_slave_status_list").html(con);
|
||||
|
||||
$('.db_error').click(function(){
|
||||
$(".btn_delete_slave").click(function(){
|
||||
var id = $(this).data('id');
|
||||
var v = rdata.data[id];
|
||||
if ('Channel_Name' in v){
|
||||
deleteSlave(v['Channel_Name']);
|
||||
} else{
|
||||
deleteSlave();
|
||||
}
|
||||
});
|
||||
|
||||
$('.db_error').click(function(){
|
||||
var id = $(this).data('id');
|
||||
var info = rdata.data[id];
|
||||
|
||||
var err_line = "";
|
||||
err_line +="<tr>\
|
||||
<td>IO错误</td>\
|
||||
<td>"+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"</td>\
|
||||
</tr>";
|
||||
err_line +="<tr>\
|
||||
<td>SQL错误</td>\
|
||||
<td>"+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"</td>\
|
||||
</tr>";
|
||||
|
||||
err_line +="<tr>\
|
||||
<td>状态</td>\
|
||||
<td>"+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"</td>\
|
||||
</tr>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '同步异常信息',
|
||||
area: '500px',
|
||||
content:"<form class='bt-form pd20 pb70'>\
|
||||
<div class='line'>"+v['Error']+"</div>\
|
||||
<div class='bt-form-submit-btn'>\
|
||||
<button type='button' class='btn btn-success btn-sm btn-title class-copy-db-err'>复制</button>\
|
||||
area: ['600px','300px'],
|
||||
btn:['复制错误',"取消"],
|
||||
content:"<form class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div class='tablescroll'>\
|
||||
<table class='table table-hover' width='100%' cellspacing='0' cellpadding='0' border='0' style='border: 0 none;'>\
|
||||
<thead><tr>\
|
||||
<th style='width:80px;'>类型</th>\
|
||||
<th>内容</th>\
|
||||
</tr></thead>\
|
||||
<tbody>"+ err_line +"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
</form>",
|
||||
success:function(){
|
||||
copyText(v['Error']);
|
||||
$('.class-copy-db-err').click(function(){
|
||||
copyText(v['Error']);
|
||||
});
|
||||
// copyText(v['Error']);
|
||||
// $('.class-copy-db-err').click(function(){
|
||||
// copyText(v['Error']);
|
||||
// });
|
||||
},
|
||||
yes:function(){
|
||||
if (info['Last_IO_Error'] != ''){
|
||||
copyText(info['Last_IO_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Last_SQL_Error'] != ''){
|
||||
copyText(info['Last_SQL_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Slave_SQL_Running_State'] != ''){
|
||||
copyText(info['Slave_SQL_Running_State']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,7 +39,7 @@ max_connections = 500
|
||||
max_connect_errors = 100
|
||||
open_files_limit = 65535
|
||||
|
||||
skip-name-resolve=1
|
||||
skip_name_resolve=1
|
||||
#skip-grant-tables
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
|
||||
@@ -18,6 +18,7 @@ basedir = {$SERVER_APP_PATH}
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
@@ -41,7 +42,7 @@ max_connections = 500
|
||||
max_connect_errors = 100
|
||||
open_files_limit = 65535
|
||||
|
||||
skip-name-resolve=1
|
||||
skip_name_resolve=1
|
||||
#skip-grant-tables
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
|
||||
@@ -16,7 +16,9 @@ basedir = {$SERVER_APP_PATH}
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
explicit_defaults_for_timestamp=true
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
|
||||
@@ -40,7 +42,7 @@ max_connect_errors = 100
|
||||
open_files_limit = 2560
|
||||
max_allowed_packet = 128M
|
||||
|
||||
skip_name_resolve = 1
|
||||
skip_name_resolve=1
|
||||
skip-ssl
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
@@ -79,6 +81,8 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
@@ -95,7 +99,7 @@ innodb_file_per_table = 1
|
||||
innodb_large_prefix = 1
|
||||
|
||||
secure-file-priv={$SERVER_APP_PATH}/tmp
|
||||
|
||||
#secure-file-priv=disabled
|
||||
[mysqldump]
|
||||
quick
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ default-character-set = UTF8MB4
|
||||
[mysqld]
|
||||
!include {$SERVER_APP_PATH}/etc/mode/classic.cnf
|
||||
|
||||
sha256_password_private_key_path=mysql.pem
|
||||
sha256_password_public_key_path=mysql.pub
|
||||
sha256_password_private_key_path={$SERVER_APP_PATH}/data/mysql.pem
|
||||
sha256_password_public_key_path={$SERVER_APP_PATH}/data/mysql.pub
|
||||
authentication_policy=mysql_native_password
|
||||
|
||||
pid-file = {$SERVER_APP_PATH}/data/mysql.pid
|
||||
@@ -20,6 +20,7 @@ basedir = {$SERVER_APP_PATH}
|
||||
datadir = {$SERVER_APP_PATH}/data
|
||||
log-error = {$SERVER_APP_PATH}/data/error.log
|
||||
server-id = {$SERVER_ID}
|
||||
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
|
||||
|
||||
default_storage_engine = InnoDB
|
||||
|
||||
@@ -40,7 +41,7 @@ max_connect_errors = 100
|
||||
open_files_limit = 2560
|
||||
max_allowed_packet = 128M
|
||||
|
||||
skip_name_resolve = 1
|
||||
skip_name_resolve=1
|
||||
#skip-networking
|
||||
#skip-external-locking
|
||||
#loose-skip-innodb
|
||||
@@ -77,6 +78,8 @@ replicate-ignore-db = performance_schema
|
||||
replicate-ignore-db = mysql
|
||||
replicate-ignore-db = test
|
||||
|
||||
master_info_repository = table
|
||||
relay_log_info_repository = table
|
||||
|
||||
innodb_data_home_dir = {$SERVER_APP_PATH}/data
|
||||
innodb_data_file_path = ibdata1:10M:autoextend
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<p onclick="dbList()">管理列表</p>
|
||||
<p onclick="masterOrSlaveConf($('.plugin_version').attr('version'))">主从配置</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="bt-w-con pd15" style="height:555px;overflow: auto;">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+233
-189
@@ -36,6 +36,10 @@ def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getSPluginDir():
|
||||
return '/www/server/mdserver-web/plugins/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
@@ -85,6 +89,14 @@ def getDbPort():
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getDbServerId():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
rep = 'server-id\s*=\s*(.*)'
|
||||
tmp = re.search(rep, content)
|
||||
return tmp.groups()[0].strip()
|
||||
|
||||
|
||||
def getSocketFile():
|
||||
file = getConf()
|
||||
content = mw.readFile(file)
|
||||
@@ -167,7 +179,6 @@ def pMysqlDb():
|
||||
|
||||
def makeInitRsaKey(version=''):
|
||||
datadir = getServerDir() + "/data"
|
||||
|
||||
mysql_pem = datadir + "/mysql.pem"
|
||||
if not os.path.exists(mysql_pem):
|
||||
rdata = mw.execShell(
|
||||
@@ -176,12 +187,11 @@ def makeInitRsaKey(version=''):
|
||||
rdata = mw.execShell(
|
||||
'cd ' + datadir + ' && openssl rsa -in mysql.pem -pubout -out mysql.pub')
|
||||
# print(rdata)
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
mw.execShell('cd ' + datadir + ' && chmod 400 mysql.pem')
|
||||
mw.execShell('cd ' + datadir + ' && chmod 444 mysql.pub')
|
||||
mw.execShell('cd ' + datadir + ' && chown mysql:mysql mysql.pem')
|
||||
mw.execShell('cd ' + datadir + ' && chown mysql:mysql mysql.pub')
|
||||
if not mw.isAppleSystem():
|
||||
mw.execShell('cd ' + datadir + ' && chmod 400 mysql.pem')
|
||||
mw.execShell('cd ' + datadir + ' && chmod 444 mysql.pub')
|
||||
mw.execShell('cd ' + datadir + ' && chown mysql:mysql mysql.pem')
|
||||
mw.execShell('cd ' + datadir + ' && chown mysql:mysql mysql.pub')
|
||||
|
||||
|
||||
def initDreplace(version=''):
|
||||
@@ -251,6 +261,14 @@ def initDreplace(version=''):
|
||||
return file_bin
|
||||
|
||||
|
||||
def process_status():
|
||||
cmd = "ps -ef|grep mysql |grep -v grep | grep -v python | awk '{print $2}'"
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
|
||||
def status(version=''):
|
||||
path = getConf()
|
||||
if not os.path.exists(path):
|
||||
@@ -383,7 +401,7 @@ def initMysql57Data():
|
||||
myconf = serverdir + "/etc/my.cnf"
|
||||
user = pGetDbUser()
|
||||
cmd = 'cd ' + serverdir + ' && ./bin/mysqld --defaults-file=' + myconf + \
|
||||
' --initialize-insecure --explicit_defaults_for_timestamp'
|
||||
' --initialize-insecure --explicit_defaults_for_timestamp --user=mysql'
|
||||
data = mw.execShell(cmd)
|
||||
# print(data)
|
||||
return False
|
||||
@@ -450,7 +468,7 @@ def initMysqlPwd():
|
||||
|
||||
|
||||
def initMysql8Pwd():
|
||||
time.sleep(2)
|
||||
time.sleep(8)
|
||||
|
||||
serverdir = getServerDir()
|
||||
myconf = serverdir + "/etc/my.cnf"
|
||||
@@ -540,7 +558,12 @@ def my8cmd(version, method):
|
||||
else:
|
||||
mw.execShell('systemctl start mysql')
|
||||
|
||||
initMysql8Pwd()
|
||||
for x in range(10):
|
||||
mydb_status = process_status()
|
||||
if mydb_status == 'start':
|
||||
initMysql8Pwd()
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
if mw.isAppleSystem():
|
||||
cmd_init_stop = init_file + ' stop'
|
||||
@@ -562,11 +585,11 @@ def my8cmd(version, method):
|
||||
|
||||
|
||||
def appCMD(version, action):
|
||||
makeInitRsaKey(version)
|
||||
if version == '8.0' or version == '5.7':
|
||||
status = my8cmd(version, action)
|
||||
else:
|
||||
status = myOp(version, action)
|
||||
makeInitRsaKey(version)
|
||||
return status
|
||||
|
||||
|
||||
@@ -791,15 +814,15 @@ def isSqlError(mysqlMsg):
|
||||
return mw.returnJson(False, "Can't connect to MySQL server on '127.0.0.1' (61)")
|
||||
if "using password:" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库密码错误,在管理列表-点击【修复】!')
|
||||
if "1045" in mysqlMsg:
|
||||
if "1045," in mysqlMsg:
|
||||
return mw.returnJson(False, '连接错误!')
|
||||
if "SQL syntax" in mysqlMsg:
|
||||
return mw.returnJson(False, 'SQL语法错误!')
|
||||
if "Connection refused" in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库连接失败,请检查数据库服务是否启动!')
|
||||
if "1133" in mysqlMsg:
|
||||
if "1133," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库用户不存在!')
|
||||
if "1007" in mysqlMsg:
|
||||
if "1007," in mysqlMsg:
|
||||
return mw.returnJson(False, '数据库已经存在!')
|
||||
return None
|
||||
|
||||
@@ -1876,13 +1899,14 @@ def getMasterStatus(version=''):
|
||||
data = {}
|
||||
data['mode'] = recognizeDbMode()
|
||||
data['status'] = master_status
|
||||
data['slave_status'] = False
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
|
||||
# print(dlist[0])
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
data['slave_status'] = True
|
||||
for v in dlist:
|
||||
if v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes':
|
||||
data['slave_status'] = True
|
||||
|
||||
return mw.returnJson(master_status, '设置成功', data)
|
||||
except Exception as e:
|
||||
@@ -2046,27 +2070,34 @@ def getMasterRepSlaveUserCmd(version):
|
||||
|
||||
mode = recognizeDbMode()
|
||||
|
||||
sid = getDbServerId()
|
||||
channel_name = ""
|
||||
if sid != '':
|
||||
channel_name = " for channel 'r{}';".format(sid)
|
||||
|
||||
if mode == "gtid":
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1" + channel_name
|
||||
if version == '8.0':
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + "', MASTER_AUTO_POSITION=1"
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_AUTO_POSITION=1" + channel_name
|
||||
else:
|
||||
sql = "CHANGE MASTER TO MASTER_HOST='" + ip + "', MASTER_PORT=" + port + ", MASTER_USER='" + \
|
||||
clist[0]['username'] + "', MASTER_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', MASTER_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',MASTER_LOG_POS=" + str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
if version == "8.0":
|
||||
sql = "CHANGE REPLICATION SOURCE TO SOURCE_HOST='" + ip + "', SOURCE_PORT=" + port + ", SOURCE_USER='" + \
|
||||
clist[0]['username'] + "', SOURCE_PASSWORD='" + \
|
||||
clist[0]['password'] + \
|
||||
"', SOURCE_LOG_FILE='" + mstatus[0]["File"] + \
|
||||
"',SOURCE_LOG_POS=" + str(mstatus[0]["Position"])
|
||||
"',SOURCE_LOG_POS=" + \
|
||||
str(mstatus[0]["Position"]) + channel_name
|
||||
|
||||
data = {}
|
||||
data['cmd'] = sql
|
||||
@@ -2337,48 +2368,17 @@ def updateSlaveSSH(version=''):
|
||||
|
||||
|
||||
def getSlaveList(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
ret = []
|
||||
for x in range(0, len(dlist)):
|
||||
tmp = {}
|
||||
tmp['Master_User'] = dlist[x]["Master_User"]
|
||||
tmp['Master_Host'] = dlist[x]["Master_Host"]
|
||||
tmp['Master_Port'] = dlist[x]["Master_Port"]
|
||||
tmp['Master_Log_File'] = dlist[x]["Master_Log_File"]
|
||||
tmp['Slave_IO_Running'] = dlist[x]["Slave_IO_Running"]
|
||||
tmp['Slave_SQL_Running'] = dlist[x]["Slave_SQL_Running"]
|
||||
tmp['Last_Error'] = dlist[x]["Last_Error"]
|
||||
tmp['Last_IO_Error'] = dlist[x]["Last_IO_Error"]
|
||||
tmp['Last_SQL_Error'] = dlist[x]["Last_SQL_Error"]
|
||||
tmp['Slave_SQL_Running_State'] = dlist[x]["Slave_SQL_Running_State"]
|
||||
|
||||
tmp['Error'] = ''
|
||||
if tmp['Last_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_Error']
|
||||
|
||||
if tmp['Last_IO_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_IO_Error']
|
||||
|
||||
if tmp['Last_SQL_Error'] != '':
|
||||
tmp['Error'] = tmp['Last_SQL_Error']
|
||||
|
||||
if tmp['Error'] == '':
|
||||
tmp['Error'] = tmp['Slave_SQL_Running_State']
|
||||
|
||||
ret.append(tmp)
|
||||
data = {}
|
||||
data['data'] = ret
|
||||
|
||||
data['data'] = dlist
|
||||
return mw.getJson(data)
|
||||
|
||||
|
||||
def getSlaveSyncCmd(version=''):
|
||||
|
||||
root = mw.getRunDir()
|
||||
cmd = 'cd ' + root + ' && python3 ' + root + \
|
||||
'/plugins/mysql/index.py do_full_sync {"db":"all"}'
|
||||
'/plugins/mysql/index.py do_full_sync {"db":"all","sign",""}'
|
||||
return mw.returnJson(True, 'ok', cmd)
|
||||
|
||||
|
||||
@@ -2413,111 +2413,152 @@ def makeSyncUsercmd(u, version=''):
|
||||
return sql
|
||||
|
||||
|
||||
def parseSlaveSyncCmd(cmd):
|
||||
a = {}
|
||||
if cmd.lower().find('for') > 0:
|
||||
cmd_tmp = cmd.split('for')
|
||||
cmd = cmd_tmp[0].strip()
|
||||
|
||||
pattern_c = r"channel \'(.*)\';"
|
||||
match_val = re.match(pattern_c, cmd_tmp[1].strip(), re.I)
|
||||
if match_val:
|
||||
m_groups = match_val.groups()
|
||||
a['channel'] = m_groups[0]
|
||||
vlist = cmd.split(',')
|
||||
for i in vlist:
|
||||
tmp = i.strip()
|
||||
tmp_a = tmp.split(" ")
|
||||
real_tmp = tmp_a[len(tmp_a) - 1]
|
||||
kv = real_tmp.split("=")
|
||||
a[kv[0]] = kv[1].replace("'", '').replace("'", '').replace(";", '')
|
||||
return a
|
||||
|
||||
|
||||
def initSlaveStatusSyncUser(version=''):
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) < 1:
|
||||
slave_data = conn.field('ip,port,user,pass,mode,cmd').select()
|
||||
if len(slave_data) < 1:
|
||||
return mw.returnJson(False, '需要先添加同步用户配置!')
|
||||
|
||||
# print(data)
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
u = data
|
||||
|
||||
mode_name = 'classic'
|
||||
if u['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
pdb = pMysqlDb()
|
||||
if len(slave_data) == 1:
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
msg = ''
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != mode_name:
|
||||
return mw.returnJson(False, '同步模式不一致!')
|
||||
for x in range(len(slave_data)):
|
||||
slave_t = slave_data[x]
|
||||
mode_name = 'classic'
|
||||
base_t = 'IP:' + slave_t['ip'] + ",PORT:" + \
|
||||
slave_t['port'] + ",USER:" + slave_t['user']
|
||||
|
||||
if u['cmd'] == '' and local_mode == 'gtid':
|
||||
sql = makeSyncUsercmd(u, version)
|
||||
# print(sql)
|
||||
t = db.query(sql)
|
||||
else:
|
||||
if u['cmd'] == '':
|
||||
return mw.returnJson(False, '经典模式下,必须手写同步命令!')
|
||||
if slave_t['mode'] == '1':
|
||||
mode_name = 'gtid'
|
||||
|
||||
if local_mode != mode_name:
|
||||
msg += base_t + '->同步模式不一致'
|
||||
continue
|
||||
|
||||
cmd_sql = slave_t['cmd']
|
||||
if cmd_sql == '':
|
||||
msg += base_t + '->同步命令不能为空'
|
||||
continue
|
||||
|
||||
try:
|
||||
pinfo = parseSlaveSyncCmd(cmd_sql)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, base_t + '->CMD同步命令不合规范!')
|
||||
# print(u['cmd'])
|
||||
t = db.query(u['cmd'])
|
||||
isError = isSqlError(t)
|
||||
if isError:
|
||||
return isError
|
||||
t = pdb.query(cmd_sql)
|
||||
isError = isSqlError(t)
|
||||
if isError:
|
||||
return isError
|
||||
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['user'], u['pass']))
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
# pdb.query("start slave user='{}' password='{}';".format(
|
||||
# u['user'], u['pass']))
|
||||
|
||||
pdb.query("start slave")
|
||||
pdb.query("start all slaves")
|
||||
|
||||
if msg == '':
|
||||
msg = '初始化成功!'
|
||||
return mw.returnJson(True, msg)
|
||||
|
||||
|
||||
def initSlaveStatusSSH(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) > 0:
|
||||
return mw.returnJson(False, '已经初始化好了zz...')
|
||||
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,port,id_rsa').find()
|
||||
ssh_list = conn.field('ip,port,id_rsa,db_user').select()
|
||||
|
||||
if len(data) < 1:
|
||||
return mw.returnJson(False, '需要先添加SSH配置!')
|
||||
if len(ssh_list) < 1:
|
||||
return mw.returnJson(False, '需要先配置【[主]SSH配置】!')
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh.txt"
|
||||
ip = data['ip']
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
local_mode = recognizeDbMode()
|
||||
|
||||
import paramiko
|
||||
paramiko.util.log_to_file('paramiko.log')
|
||||
ssh = paramiko.SSHClient()
|
||||
|
||||
try:
|
||||
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
for data in ssh_list:
|
||||
ip = data['ip']
|
||||
SSH_PRIVATE_KEY = "/tmp/t_ssh_" + ip + ".txt"
|
||||
master_port = data['port']
|
||||
mw.writeFile(SSH_PRIVATE_KEY, data['id_rsa'].replace('\\n', '\n'))
|
||||
mw.execShell("chmod 600 " + SSH_PRIVATE_KEY)
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
try:
|
||||
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY)
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(hostname=ip, port=int(master_port),
|
||||
username='root', pkey=key)
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
cmd_data = json.loads(result)
|
||||
db_user = data['db_user']
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \
|
||||
getSPluginDir() + \
|
||||
'/index.py get_master_rep_slave_user_cmd {"username":"' + \
|
||||
db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
if result.strip() == "":
|
||||
return mw.returnJson(False, '[主][' + ip + ']:获取同步命令失败!')
|
||||
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主]:' + cmd_data['msg'])
|
||||
cmd_data = json.loads(result)
|
||||
if not cmd_data['status']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:' + cmd_data['msg'])
|
||||
|
||||
local_mode = recognizeDbMode()
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '主【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
if local_mode != cmd_data['data']['mode']:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:【{}】从【{}】,运行模式不一致!'.format(cmd_data['data']['mode'], local_mode))
|
||||
|
||||
u = cmd_data['data']['info']
|
||||
ps = u['username'] + "|" + u['password']
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
u = cmd_data['data']['info']
|
||||
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
ps = u['username'] + "|" + u['password']
|
||||
print(ps)
|
||||
conn.where('ip=?', (ip,)).setField('ps', ps)
|
||||
db.query('stop slave')
|
||||
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
u['username'], u['password']))
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, 'SSH认证配置连接失败!' + str(e))
|
||||
# 保证同步IP一致
|
||||
cmd = cmd_data['data']['cmd']
|
||||
if cmd.find('SOURCE_HOST') > -1:
|
||||
cmd = re.sub(r"SOURCE_HOST='(.*?)'",
|
||||
"SOURCE_HOST='" + ip + "'", cmd, 1)
|
||||
|
||||
ssh.close()
|
||||
time.sleep(1)
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
if cmd.find('MASTER_HOST') > -1:
|
||||
cmd = re.sub(r"MASTER_HOST='(.*?)'",
|
||||
"MASTER_HOST='" + ip + "'", cmd, 1)
|
||||
db.query(cmd)
|
||||
ssh.close()
|
||||
if os.path.exists(SSH_PRIVATE_KEY):
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
except Exception as e:
|
||||
return mw.returnJson(False, '[主][' + ip + ']:SSH认证配置连接失败!' + str(e))
|
||||
db.query('start slave')
|
||||
return mw.returnJson(True, '初始化成功!')
|
||||
|
||||
|
||||
@@ -2527,60 +2568,37 @@ def setSlaveStatus(version=''):
|
||||
return mw.returnJson(False, '需要先设置同步配置')
|
||||
|
||||
mode = mw.readFile(mode_file)
|
||||
if mode == 'ssh':
|
||||
return setSlaveStatusSSH(version)
|
||||
if mode == 'sync-user':
|
||||
return setSlaveStatusSyncUser(version)
|
||||
|
||||
|
||||
def setSlaveStatusSyncUser(version=''):
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
pdb = pMysqlDb()
|
||||
dlist = pdb.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加同步账户或者执行初始化!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
for v in dlist:
|
||||
connection_name = ''
|
||||
cmd = "slave"
|
||||
if 'Channel_Name' in v:
|
||||
ch_name = v['Channel_Name']
|
||||
cmd = "slave for channel '{}'".format(ch_name)
|
||||
|
||||
db.query("start slave")
|
||||
# db.query("start slave user='{}' password='{}';".format(user, apass))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def setSlaveStatusSSH(version=''):
|
||||
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('show slave status')
|
||||
if len(dlist) == 0:
|
||||
return mw.returnJson(False, '需要手动添加主服务命令或者执行初始化!')
|
||||
|
||||
if len(dlist) > 0 and (dlist[0]["Slave_IO_Running"] == 'Yes' or dlist[0]["Slave_SQL_Running"] == 'Yes'):
|
||||
db.query('stop slave')
|
||||
else:
|
||||
ip = dlist[0]['Master_Host']
|
||||
conn = pSqliteDb('slave_id_rsa')
|
||||
data = conn.field('ip,ps').where("ip=?", (ip,)).find()
|
||||
if len(data) == 0:
|
||||
return mw.returnJson(False, '没有数据无法重启!')
|
||||
u = data['ps'].split("|")
|
||||
db.query("start slave user='{}' password='{}';".format(u[0], u[1]))
|
||||
if (v["Slave_IO_Running"] == 'Yes' or v["Slave_SQL_Running"] == 'Yes'):
|
||||
pdb.query("stop {}".format(cmd))
|
||||
else:
|
||||
pdb.query("start {}".format(cmd))
|
||||
|
||||
return mw.returnJson(True, '设置成功!')
|
||||
|
||||
|
||||
def deleteSlave(version=''):
|
||||
args = getArgs()
|
||||
db = pMysqlDb()
|
||||
dlist = db.query('stop slave')
|
||||
dlist = db.query('reset slave all')
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
db.query("stop slave for channel '{}'".format(sign))
|
||||
db.query("reset slave all for channel '{}'".format(sign))
|
||||
else:
|
||||
db.query('stop slave')
|
||||
db.query('reset slave all')
|
||||
|
||||
return mw.returnJson(True, '删除成功!')
|
||||
|
||||
|
||||
@@ -2617,11 +2635,13 @@ def dumpMysqlData(version=''):
|
||||
|
||||
############### --- 重要 同步---- ###########
|
||||
|
||||
def asyncTmpfile():
|
||||
path = '/tmp/mysql_async_status.txt'
|
||||
return path
|
||||
|
||||
|
||||
def writeDbSyncStatus(data):
|
||||
path = '/tmp/db_async_status.txt'
|
||||
# status_data['code'] = 1
|
||||
# status_data['msg'] = '主服务器备份完成...'
|
||||
# status_data['progress'] = 30
|
||||
path = asyncTmpfile()
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
@@ -2639,16 +2659,22 @@ def doFullSync(version=''):
|
||||
|
||||
def doFullSyncUser(version=''):
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
conn = pSqliteDb('slave_sync_user')
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
if sync_sign != '':
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = conn.field('ip,port,user,pass,mode,cmd').find()
|
||||
|
||||
user = data['user']
|
||||
apass = data['pass']
|
||||
port = data['port']
|
||||
@@ -2685,21 +2711,30 @@ def doFullSyncUser(version=''):
|
||||
db.query("start slave")
|
||||
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
os.system("rm -rf " + bak_file)
|
||||
|
||||
if os.path.exists(bak_file):
|
||||
os.system("rm -rf " + bak_file)
|
||||
return True
|
||||
|
||||
|
||||
def doFullSyncSSH(version=''):
|
||||
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['db'])
|
||||
data = checkArgs(args, ['db', 'sign'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
sync_db = args['db']
|
||||
sync_sign = args['sign']
|
||||
|
||||
db = pMysqlDb()
|
||||
|
||||
id_rsa_conn = pSqliteDb('slave_id_rsa')
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
if sync_sign != '':
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').where(
|
||||
'ip=?', (sync_sign,)).find()
|
||||
else:
|
||||
data = id_rsa_conn.field('ip,port,db_user,id_rsa').find()
|
||||
|
||||
SSH_PRIVATE_KEY = "/tmp/mysql_sync_id_rsa.txt"
|
||||
id_rsa = data['id_rsa'].replace('\\n', '\n')
|
||||
@@ -2741,7 +2776,8 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 0, 'msg': '登录Master成功...', 'progress': 5})
|
||||
|
||||
dbname = args['db']
|
||||
cmd = "cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
cmd = "cd /www/server/mdserver-web && source bin/activate && python3 " + \
|
||||
getSPluginDir() + "/index.py dump_mysql_data {\"db\":'" + dbname + "'}"
|
||||
print(cmd)
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
@@ -2764,7 +2800,10 @@ def doFullSyncSSH(version=''):
|
||||
if copy_status == None:
|
||||
writeDbSyncStatus({'code': 2, 'msg': '数据同步本地完成...', 'progress': 40})
|
||||
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 plugins/mysql/index.py get_master_rep_slave_user_cmd {"username":"' + db_user + '","db":""}'
|
||||
cmd = 'cd /www/server/mdserver-web && source bin/activate && python3 ' + \
|
||||
getSPluginDir() + \
|
||||
'/index.py get_master_rep_slave_user_cmd {"username":"' + \
|
||||
db_user + '","db":""}'
|
||||
stdin, stdout, stderr = ssh.exec_command(cmd)
|
||||
result = stdout.read()
|
||||
result = result.decode('utf-8')
|
||||
@@ -2806,8 +2845,9 @@ def doFullSyncSSH(version=''):
|
||||
writeDbSyncStatus({'code': 5, 'msg': '导入数据失败...', 'progress': 100})
|
||||
return 'fail'
|
||||
|
||||
db.query("start slave user='{}' password='{}';".format(
|
||||
uinfo['username'], uinfo['password']))
|
||||
# "start slave user='{}' password='{}';".format(uinfo['username'], uinfo['password'])
|
||||
|
||||
db.query("start slave")
|
||||
writeDbSyncStatus({'code': 6, 'msg': '从库重启完成...', 'progress': 100})
|
||||
|
||||
os.system("rm -rf " + SSH_PRIVATE_KEY)
|
||||
@@ -2821,12 +2861,16 @@ def fullSync(version=''):
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
status_file = '/tmp/db_async_status.txt'
|
||||
sign = ''
|
||||
if 'sign' in args:
|
||||
sign = args['sign']
|
||||
|
||||
status_file = asyncTmpfile()
|
||||
if args['begin'] == '1':
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + \
|
||||
getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + args['db'] + '"} &'
|
||||
print(cmd)
|
||||
cmd = 'cd ' + mw.getRunDir() + ' && python3 ' + getPluginDir() + \
|
||||
'/index.py do_full_sync {"db":"' + \
|
||||
args['db'] + '","sign":"' + sign + '"} &'
|
||||
# print(cmd)
|
||||
mw.execShell(cmd)
|
||||
return json.dumps({'code': 0, 'msg': '同步数据中!', 'progress': 0})
|
||||
|
||||
|
||||
+164
-80
@@ -162,34 +162,6 @@ function myPort(){
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
//数据库存储信置
|
||||
function changeMySQLDataPath(act) {
|
||||
if (act != undefined) {
|
||||
layer.confirm(lan.soft.mysql_to_msg, { closeBtn: 2, icon: 3 }, function() {
|
||||
var datadir = $("#datadir").val();
|
||||
var data = 'datadir=' + datadir;
|
||||
var loadT = layer.msg(lan.soft.mysql_to_msg1, { icon: 16, time: 0, shade: [0.3, '#000'] });
|
||||
$.post('/database?action=SetDataDir', data, function(rdata) {
|
||||
layer.close(loadT)
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 5 });
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
$.post('/database?action=GetMySQLInfo', '', function(rdata) {
|
||||
var LimitCon = '<p class="conf_p">\
|
||||
<input id="datadir" class="phpUploadLimit bt-input-text mr5" style="width:350px;" type="text" value="' + rdata.datadir + '" name="datadir">\
|
||||
<span onclick="ChangePath(\'datadir\')" class="glyphicon glyphicon-folder-open cursor mr20" style="width:auto"></span><button class="btn btn-success btn-sm" onclick="changeMySQLDataPath(1)">' + lan.soft.mysql_to + '</button>\
|
||||
</p>';
|
||||
$(".soft-man-con").html(LimitCon);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//数据库配置状态
|
||||
function myPerfOpt() {
|
||||
//获取MySQL配置
|
||||
@@ -1691,12 +1663,12 @@ function getMasterRepSlaveListPage(){
|
||||
}
|
||||
|
||||
|
||||
function deleteSlave(){
|
||||
myPost('delete_slave', {}, function(data){
|
||||
function deleteSlave(sign){
|
||||
myPost('delete_slave', {sign:sign}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
showMsg(rdata['msg'], function(){
|
||||
masterOrSlaveConf();
|
||||
},{},3000);
|
||||
},{icon:rdata.status?1:2,time:3000},3000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1704,28 +1676,73 @@ function deleteSlave(){
|
||||
function getFullSyncStatus(db){
|
||||
var timeId = null;
|
||||
|
||||
var btn = '<div class="table_toolbar" style="left:0px;"><span data-status="init" class="sync btn btn-default btn-sm" id="begin_full_sync" title="">开始</span></div>';
|
||||
var loadOpen = layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
"+btn+"\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
myPost('get_slave_list', {page:1,page_size:100}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var rsource = rdata.data;
|
||||
|
||||
if (db == 'ALL' && rsource.length>1){
|
||||
layer.msg("多主不支持该模式!",{icon:2});
|
||||
return;
|
||||
}
|
||||
|
||||
var dataSource = '';
|
||||
if (rsource.length>1){
|
||||
var sourceList = '';
|
||||
for (var i = 0; i < rsource.length; i++) {
|
||||
if ('Channel_Name' in rsource[i]){
|
||||
sourceList += '<option val="'+rsource[i]['Master_Host']+'">'+rsource[i]['Master_Host']+'</option>';
|
||||
}
|
||||
}
|
||||
|
||||
dataSource = "<p class='line' style='text-align:center;'>\
|
||||
<span>同步数据源:</span>\
|
||||
<select class='bt-input-text' name='data_source' style='width:200px;'>" + sourceList + "</select>\
|
||||
</p>";
|
||||
}
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '全量同步['+db+']',
|
||||
area: '500px',
|
||||
content:"<div class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
"+dataSource+"\
|
||||
<span id='full_msg'></span>\
|
||||
<div class='progress'>\
|
||||
<div class='progress-bar' role='progressbar' aria-valuenow='0' aria-valuemin='0' aria-valuemax='100' style='min-width: 2em;'>0%</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='table_toolbar' style='left:0px;'>\
|
||||
<span data-status='init' class='sync btn btn-default btn-sm' id='begin_full_sync'>开始</span>\
|
||||
</div>\
|
||||
</div>",
|
||||
cancel: function(){
|
||||
clearInterval(timeId);
|
||||
},
|
||||
success:function(){
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).data('status');
|
||||
var sign = '';
|
||||
if (dataSource !=''){
|
||||
sign = $('select[name="data_source"]').val();
|
||||
}
|
||||
if (val == 'init'){
|
||||
fullSync(db, sign, 1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,sign,0);
|
||||
}, 1000);
|
||||
$(this).data('status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..",{icon:0});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function fullSync(db,begin){
|
||||
function fullSync(db,sign,begin){
|
||||
|
||||
myPostN('full_sync', {db:db,begin:begin}, function(data){
|
||||
myPostN('full_sync', {db:db,sign:sign,begin:begin}, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
$('#full_msg').text(rdata['msg']);
|
||||
$('.progress-bar').css('width',rdata['progress']+'%');
|
||||
@@ -1738,19 +1755,6 @@ function getFullSyncStatus(db){
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$('#begin_full_sync').click(function(){
|
||||
var val = $(this).attr('data-status');
|
||||
if (val == 'init'){
|
||||
fullSync(db,1);
|
||||
timeId = setInterval(function(){
|
||||
fullSync(db,0);
|
||||
}, 1000);
|
||||
$(this).attr('data-status','starting');
|
||||
} else {
|
||||
layer.msg("正在同步中..");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addSlaveSSH(ip=''){
|
||||
@@ -1920,18 +1924,29 @@ function addSlaveSyncUser(ip=''){
|
||||
<div class='line'><span class='tname'>同步账户</span><div class='info-r'><input name='user' class='bt-input-text mr5' type='text' style='width:330px;' value='"+user+"'></div></div>\
|
||||
<div class='line'><span class='tname'>同步密码</span><div class='info-r'><input name='pass' class='bt-input-text mr5' type='text' style='width:330px;' value='"+pass+"'></div></div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>CMD[最好填好]</span>\
|
||||
<span class='tname'>CMD[必须填写]</span>\
|
||||
<div class='info-r'><textarea class='bt-input-text mr5' row='20' cols='30' name='cmd' style='width:330px;height:150px;'></textarea></div>\
|
||||
</div>\
|
||||
<input type='hidden' name='mode' value='"+mode+"' />\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('textarea[name="cmd"]').html(cmd);
|
||||
|
||||
$('textarea[name="cmd"]').change(function(){
|
||||
var val = $(this).val();
|
||||
var vlist = val.split(',');
|
||||
var a = {};
|
||||
if (val.toLowerCase().indexOf('for')>0){
|
||||
cmd_tmp = val.split('for');
|
||||
val = cmd_tmp[0].trim();
|
||||
|
||||
const channel_str = cmd_tmp[1].trim();
|
||||
const ch_reg = /channel \'(.*)\';/;
|
||||
var match_val = channel_str.match(ch_reg);
|
||||
if (match_val.length>1){
|
||||
a['channel'] = match_val[1];
|
||||
}
|
||||
}
|
||||
|
||||
var vlist = val.split(',');
|
||||
for (var i in vlist) {
|
||||
var tmp = toTrim(vlist[i]);
|
||||
var tmp_a = tmp.split(" ");
|
||||
@@ -2098,7 +2113,7 @@ function getSlaveUserList(){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: '同步账户列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2122,7 +2137,7 @@ function getSlaveSSHList(page=1){
|
||||
layerId = layer.open({
|
||||
type: 1,
|
||||
title: 'SSH列表',
|
||||
area: '500px',
|
||||
area: '600px',
|
||||
content:"<div class='bt-form pd20 c6'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div><table class='table table-hover get-slave-ssh-list'>\
|
||||
@@ -2230,10 +2245,16 @@ function masterOrSlaveConf(version=''){
|
||||
myPost('get_slave_list', _data, function(data){
|
||||
var rdata = $.parseJSON(data.data);
|
||||
var list = '';
|
||||
|
||||
var isHasSign = false;
|
||||
for(i in rdata.data){
|
||||
|
||||
var v = rdata.data[i];
|
||||
var status = "<a class='btlink db_error'>异常</>";
|
||||
if ('Channel_Name' in v){
|
||||
isHasSign = true;
|
||||
}
|
||||
|
||||
var status = "<a data-id="+i+" class='btlink db_error'>异常</>";
|
||||
if (v['Slave_SQL_Running'] == 'Yes' && v['Slave_IO_Running'] == 'Yes'){
|
||||
status = "正常";
|
||||
}
|
||||
@@ -2245,13 +2266,23 @@ function masterOrSlaveConf(version=''){
|
||||
list += '<td>' + rdata.data[i]['Master_Log_File'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_IO_Running'] +'</td>';
|
||||
list += '<td>' + rdata.data[i]['Slave_SQL_Running'] +'</td>';
|
||||
|
||||
if (isHasSign){
|
||||
list += '<td>' + v['Channel_Name'] +'</td>';
|
||||
}
|
||||
|
||||
list += '<td>' + status +'</td>';
|
||||
list += '<td style="text-align:right">' +
|
||||
'<a href="javascript:;" class="btlink" onclick="deleteSlave()" title="删除">删除</a>' +
|
||||
'<a data-id="'+i+'" href="javascript:;" class="btlink btn_delete_slave" title="删除">删除</a>' +
|
||||
'</td>';
|
||||
list += '</tr>';
|
||||
}
|
||||
|
||||
var signThead_th = '';
|
||||
if (isHasSign){
|
||||
var signThead_th = '<th>标识</th>';
|
||||
}
|
||||
|
||||
var con = '<div class="divtable mtb10">\
|
||||
<div class="tablescroll">\
|
||||
<table id="DataBody" class="table table-hover" width="100%" cellspacing="0" cellpadding="0" border="0" style="border: 0 none;">\
|
||||
@@ -2262,6 +2293,7 @@ function masterOrSlaveConf(version=''){
|
||||
<th>日志</th>\
|
||||
<th>IO</th>\
|
||||
<th>SQL</th>\
|
||||
'+signThead_th+'\
|
||||
<th>状态</th>\
|
||||
<th style="text-align:right;">操作</th></tr></thead>\
|
||||
<tbody>\
|
||||
@@ -2276,22 +2308,74 @@ function masterOrSlaveConf(version=''){
|
||||
// </div>
|
||||
$(".table_slave_status_list").html(con);
|
||||
|
||||
$('.db_error').click(function(){
|
||||
$(".btn_delete_slave").click(function(){
|
||||
var id = $(this).data('id');
|
||||
var v = rdata.data[id];
|
||||
if ('Channel_Name' in v){
|
||||
deleteSlave(v['Channel_Name']);
|
||||
} else{
|
||||
deleteSlave();
|
||||
}
|
||||
});
|
||||
|
||||
$('.db_error').click(function(){
|
||||
var id = $(this).data('id');
|
||||
var info = rdata.data[id];
|
||||
|
||||
var err_line = "";
|
||||
err_line +="<tr>\
|
||||
<td>IO错误</td>\
|
||||
<td>"+ (info['Last_IO_Error'] == '' ? '无':info['Last_IO_Error'])+"</td>\
|
||||
</tr>";
|
||||
err_line +="<tr>\
|
||||
<td>SQL错误</td>\
|
||||
<td>"+(info['Last_SQL_Error'] == '' ? '无':info['Last_SQL_Error'])+"</td>\
|
||||
</tr>";
|
||||
|
||||
err_line +="<tr>\
|
||||
<td>状态</td>\
|
||||
<td>"+(info['Slave_SQL_Running_State'] == '' ? '无':info['Slave_SQL_Running_State']) +"</td>\
|
||||
</tr>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
title: '同步异常信息',
|
||||
area: '500px',
|
||||
content:"<form class='bt-form pd20 pb70'>\
|
||||
<div class='line'>"+v['Error']+"</div>\
|
||||
<div class='bt-form-submit-btn'>\
|
||||
<button type='button' class='btn btn-success btn-sm btn-title class-copy-db-err'>复制</button>\
|
||||
area: ['600px','300px'],
|
||||
btn:['复制错误',"取消"],
|
||||
content:"<form class='bt-form pd15'>\
|
||||
<div class='divtable mtb10'>\
|
||||
<div class='tablescroll'>\
|
||||
<table class='table table-hover' width='100%' cellspacing='0' cellpadding='0' border='0' style='border: 0 none;'>\
|
||||
<thead><tr>\
|
||||
<th style='width:80px;'>类型</th>\
|
||||
<th>内容</th>\
|
||||
</tr></thead>\
|
||||
<tbody>"+ err_line +"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
</form>",
|
||||
success:function(){
|
||||
copyText(v['Error']);
|
||||
$('.class-copy-db-err').click(function(){
|
||||
copyText(v['Error']);
|
||||
});
|
||||
// copyText(v['Error']);
|
||||
// $('.class-copy-db-err').click(function(){
|
||||
// copyText(v['Error']);
|
||||
// });
|
||||
},
|
||||
yes:function(){
|
||||
if (info['Last_IO_Error'] != ''){
|
||||
copyText(info['Last_IO_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Last_SQL_Error'] != ''){
|
||||
copyText(info['Last_SQL_Error']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (info['Slave_SQL_Running_State'] != ''){
|
||||
copyText(info['Slave_SQL_Running_State']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,6 +86,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.5' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -105,6 +105,7 @@ Install_mysql()
|
||||
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.6' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -118,6 +118,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '5.7' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
@@ -210,6 +210,7 @@ Install_mysql()
|
||||
make -j${cpuCore} && make install && make clean
|
||||
|
||||
if [ -d $serverPath/mysql ];then
|
||||
rm -rf ${mysqlDir}/mysql-${VERSION}
|
||||
echo '8.0' > $serverPath/mysql/version.pl
|
||||
echo '安装完成' > $install_tmp
|
||||
else
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 878 B |
Executable
+26
@@ -0,0 +1,26 @@
|
||||
<div class="bt-form">
|
||||
<div class="bt-w-main">
|
||||
<div class='plugin_version'></div>
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('nezha',$('.plugin_version').attr('version'));">面板服务</p>
|
||||
<p onclick="pluginInitD('nezha',$('.plugin_version').attr('version'));">面板自启动</p>
|
||||
<p onclick="nezha.cfg($('.plugin_version').attr('version'));">面板配置</p>
|
||||
<p onclick="pluginConfig('nezha', $('.plugin_version').attr('version'), 'conf');">面板配置文件</p>
|
||||
<p onclick="pluginService('nezha', $('.plugin_version').attr('version'), 'agent');">AGENT服务</p>
|
||||
<p onclick="pluginInitD('nezha', $('.plugin_version').attr('version'), 'agent');">AGENT自启动</p>
|
||||
<p onclick="nezha.agent_cfg($('.plugin_version').attr('version'));">AGENT配置</p>
|
||||
<p onclick="nezha.readme();">说明</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
resetPluginWinHeight(530);
|
||||
$.getScript( "/plugins/file?name=nezha&f=js/nezha.js", function(){
|
||||
nezha.init();
|
||||
pluginService('nezha');
|
||||
});
|
||||
</script>
|
||||
Executable
+364
@@ -0,0 +1,364 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import socket
|
||||
import json
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
class App:
|
||||
__setupPath = '/www/server/nezha'
|
||||
__cfg = ''
|
||||
__agent_cfg = ''
|
||||
|
||||
def __init__(self):
|
||||
self.__setupPath = self.getServerDir()
|
||||
self.__cfg = self.__setupPath + '/nezha.cfg'
|
||||
self.__agent_cfg = self.__setupPath + '/agent.cfg'
|
||||
|
||||
def getArgs(self):
|
||||
args = sys.argv[3:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
t = t.split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':', 1)
|
||||
tmp[t[0]] = t[1]
|
||||
|
||||
return tmp
|
||||
|
||||
def checkArgs(self, data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
def __release_port(self, port):
|
||||
from collections import namedtuple
|
||||
try:
|
||||
import firewall_api
|
||||
firewall_api.firewall_api().addAcceptPortArgs(port, 'nezha', 'port')
|
||||
return port
|
||||
except Exception as e:
|
||||
return "Release failed {}".format(e)
|
||||
|
||||
def openPort(self):
|
||||
for i in ["9527", "5555"]:
|
||||
self.__release_port(i)
|
||||
return True
|
||||
|
||||
def getPluginName(self):
|
||||
return 'nezha'
|
||||
|
||||
def getPluginDir(self):
|
||||
return mw.getPluginDir() + '/' + self.getPluginName()
|
||||
|
||||
def getServerDir(self):
|
||||
return mw.getServerDir() + '/' + self.getPluginName()
|
||||
|
||||
def getInitdConfTpl(self):
|
||||
path = self.getPluginDir() + "/init.d/nezha.tpl"
|
||||
return path
|
||||
|
||||
def getInitdAgentConfTpl(self):
|
||||
path = self.getPluginDir() + "/init.d/nezha-agent.tpl"
|
||||
return path
|
||||
|
||||
def getHomeDir(self):
|
||||
if mw.isAppleSystem():
|
||||
user = mw.execShell(
|
||||
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
|
||||
return '/Users/' + user
|
||||
else:
|
||||
return '/root'
|
||||
|
||||
def getRunUser(self):
|
||||
if mw.isAppleSystem():
|
||||
user = mw.execShell(
|
||||
"who | sed -n '2, 1p' |awk '{print $1}'")[0].strip()
|
||||
return user
|
||||
else:
|
||||
return 'root'
|
||||
|
||||
def status(self):
|
||||
cmd = "ps -ef|grep " + self.getPluginName() + \
|
||||
" |grep -v grep | grep -v nezha-agent | grep -v python | awk '{print $2}'"
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return "stop"
|
||||
return 'start'
|
||||
|
||||
def status_agent(self):
|
||||
cmd = "ps -ef | grep nezha-agent | grep -v grep | grep -v python | awk '{print $2}'"
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'stop'
|
||||
return 'start'
|
||||
|
||||
def contentReplace(self, content):
|
||||
|
||||
service_path = mw.getServerDir()
|
||||
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$RUN_USER}', self.getRunUser())
|
||||
content = content.replace('{$HOME_DIR}', self.getHomeDir())
|
||||
|
||||
return content
|
||||
|
||||
def initDreplace(self):
|
||||
|
||||
file_tpl = self.getInitdConfTpl()
|
||||
service_path = mw.getServerDir()
|
||||
|
||||
initD_path = self.getServerDir() + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
self.openPort()
|
||||
|
||||
file_bin = initD_path + '/' + self.getPluginName()
|
||||
|
||||
if not os.path.exists(file_bin):
|
||||
content = mw.readFile(file_tpl)
|
||||
content = self.contentReplace(content)
|
||||
mw.writeFile(file_bin, content)
|
||||
mw.execShell('chmod +x ' + file_bin)
|
||||
|
||||
# systemd
|
||||
systemDir = mw.systemdCfgDir()
|
||||
systemService = systemDir + '/nezha.service'
|
||||
systemServiceTpl = self.getPluginDir() + '/init.d/nezha.service.tpl'
|
||||
if os.path.exists(systemDir) and not os.path.exists(systemService):
|
||||
service_path = mw.getServerDir()
|
||||
se_content = mw.readFile(systemServiceTpl)
|
||||
se_content = self.contentReplace(se_content)
|
||||
mw.writeFile(systemService, se_content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_bin
|
||||
|
||||
def contentAgentReplace(self, content):
|
||||
path = self.__agent_cfg
|
||||
if os.path.exists(path):
|
||||
data = self.get_agent_cfg()
|
||||
content = content.replace('{$APP_HOST}', data['host'])
|
||||
content = content.replace('{$APP_SECRET}', data['secret'])
|
||||
|
||||
return content
|
||||
|
||||
def initDAgent(self):
|
||||
file_tpl = self.getInitdAgentConfTpl()
|
||||
|
||||
initD_path = self.getServerDir() + '/init.d'
|
||||
if not os.path.exists(initD_path):
|
||||
os.mkdir(initD_path)
|
||||
|
||||
file_agent_bin = initD_path + '/nezha-agent'
|
||||
|
||||
content = mw.readFile(file_tpl)
|
||||
content = self.contentReplace(content)
|
||||
content = self.contentAgentReplace(content)
|
||||
mw.writeFile(file_agent_bin, content)
|
||||
mw.execShell('chmod +x ' + file_agent_bin)
|
||||
|
||||
# systemd
|
||||
sysDir = mw.systemdCfgDir()
|
||||
sysService = sysDir + '/nezha-agent.service'
|
||||
sysServiceTpl = self.getPluginDir() + '/init.d/nezha-agent.service.tpl'
|
||||
service_path = mw.getServerDir()
|
||||
content = mw.readFile(sysServiceTpl)
|
||||
content = self.contentReplace(content)
|
||||
content = self.contentAgentReplace(content)
|
||||
mw.writeFile(sysService, content)
|
||||
mw.execShell('systemctl daemon-reload')
|
||||
|
||||
return file_agent_bin
|
||||
|
||||
def init_cfg(self):
|
||||
self.initDreplace()
|
||||
self.initDAgent()
|
||||
|
||||
def imOp(self, method):
|
||||
|
||||
file = self.initDreplace()
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
cmd = 'systemctl {} {}'.format(method, self.getPluginName())
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return 'fail'
|
||||
|
||||
data = mw.execShell(file + ' ' + method)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[0]
|
||||
|
||||
def start(self):
|
||||
return self.imOp('start')
|
||||
|
||||
def stop(self):
|
||||
return self.imOp('stop')
|
||||
|
||||
def restart(self):
|
||||
return self.imOp('restart')
|
||||
|
||||
def reload(self):
|
||||
return self.imOp('reload')
|
||||
|
||||
def agOp(self, method):
|
||||
file = self.initDAgent()
|
||||
|
||||
path = self.__agent_cfg
|
||||
if not os.path.exists(path):
|
||||
return '请先设置Agent配置!'
|
||||
|
||||
if not mw.isAppleSystem():
|
||||
cmd = 'systemctl {} {}'.format(method, 'nezha-agent')
|
||||
data = mw.execShell(cmd)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return 'fail'
|
||||
|
||||
data = mw.execShell(file + ' ' + method)
|
||||
if data[1] == '':
|
||||
return 'ok'
|
||||
return data[0]
|
||||
|
||||
def start_agent(self):
|
||||
return self.agOp('start')
|
||||
|
||||
def stop_agent(self):
|
||||
return self.agOp('stop')
|
||||
|
||||
def restart_agent(self):
|
||||
return self.agOp('restart')
|
||||
|
||||
def reload_agent(self):
|
||||
return self.agentOp('reload')
|
||||
|
||||
def initd_status(self):
|
||||
cmd = 'systemctl status nezha | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
def initd_install(self):
|
||||
mw.execShell('systemctl enable nezha')
|
||||
return 'ok'
|
||||
|
||||
def initd_uninstall(self):
|
||||
mw.execShell('systemctl disable nezha')
|
||||
return 'ok'
|
||||
|
||||
def initd_status_agent(self):
|
||||
cmd = 'systemctl status nezha-agent | grep loaded | grep "enabled;"'
|
||||
data = mw.execShell(cmd)
|
||||
if data[0] == '':
|
||||
return 'fail'
|
||||
return 'ok'
|
||||
|
||||
def initd_install_agent(self):
|
||||
mw.execShell('systemctl enable nezha-agent')
|
||||
return 'ok'
|
||||
|
||||
def initd_uninstall_agent(self):
|
||||
mw.execShell('systemctl disable nezha-agent')
|
||||
return 'ok'
|
||||
|
||||
def conf(self):
|
||||
return self.getServerDir() + '/dashboard/data/config.yaml'
|
||||
|
||||
def nezha_cfg(self):
|
||||
path = self.__cfg
|
||||
if not os.path.exists(path):
|
||||
d = {}
|
||||
cmd_un = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u ""'
|
||||
mw.execShell(cmd_un)
|
||||
td = mw.execShell(cmd_un)
|
||||
d['username'] = td[0].strip()
|
||||
|
||||
pwd = mw.getRandomString(16)
|
||||
cmd_pwd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -u "" -p ' + pwd
|
||||
td = mw.execShell(cmd_pwd)
|
||||
d['password'] = pwd
|
||||
|
||||
mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(d)))
|
||||
|
||||
info = mw.readFile(path)
|
||||
info = mw.deDoubleCrypt('nezha', info)
|
||||
|
||||
info = json.loads(info)
|
||||
return mw.returnJson(True, 'ok', info)
|
||||
|
||||
def nezha_save_cfg(self):
|
||||
args = self.getArgs()
|
||||
data = self.checkArgs(args, ['username', 'password'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
path = self.__cfg
|
||||
|
||||
cmd = 'cd ' + self.getServerDir() + '/dashboard && ./nezha conf -su "' + \
|
||||
args['username'] + '" -p ' + args['password']
|
||||
# print(cmd)
|
||||
t = mw.execShell(cmd)
|
||||
# print(t)
|
||||
mw.writeFile(path, mw.enDoubleCrypt('nezha', mw.getJson(args)))
|
||||
return mw.returnJson(True, '修改成功!')
|
||||
|
||||
def get_agent_cfg(self):
|
||||
path = self.__agent_cfg
|
||||
info = mw.readFile(path)
|
||||
info = mw.deDoubleCrypt('agent', info)
|
||||
info = json.loads(info)
|
||||
return info
|
||||
|
||||
def agent_cfg(self):
|
||||
path = self.__agent_cfg
|
||||
if not os.path.exists(path):
|
||||
d = {}
|
||||
d['host'] = '127.0.0.1:5555'
|
||||
d['secret'] = 'secret'
|
||||
mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(d)))
|
||||
|
||||
info = self.get_agent_cfg()
|
||||
return mw.returnJson(True, 'ok', info)
|
||||
|
||||
def agent_save_cfg(self):
|
||||
args = self.getArgs()
|
||||
data = self.checkArgs(args, ['host', 'secret'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
path = self.__agent_cfg
|
||||
mw.writeFile(path, mw.enDoubleCrypt('agent', mw.getJson(args)))
|
||||
return mw.returnJson(True, '修改成功!')
|
||||
|
||||
def run_log(self):
|
||||
return self.getServerDir() + '/logs/nezha.log'
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
classApp = App()
|
||||
try:
|
||||
data = eval("classApp." + func + "()")
|
||||
print(data)
|
||||
except Exception as e:
|
||||
print('error:' + str(e))
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"sort": 7,
|
||||
"ps": "哪吒监控面板/改造版",
|
||||
"name": "nezha",
|
||||
"title": "哪吒监控",
|
||||
"shell": "install.sh",
|
||||
"versions":["0.15.2"],
|
||||
"tip": "soft",
|
||||
"checks": "server/nezha",
|
||||
"path": "server/nezha",
|
||||
"display": 1,
|
||||
"author": "midoks",
|
||||
"date": "2023-06-26",
|
||||
"home": "https://github.com/midoks/nezha",
|
||||
"doc1": "https://nezha.wiki/",
|
||||
"type": 0,
|
||||
"pid": "5"
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Nezha Agent
|
||||
After=syslog.target
|
||||
#After=network.target
|
||||
#After=nezha-dashboard.service
|
||||
|
||||
[Service]
|
||||
# Modify these two values and uncomment them if you have
|
||||
# repos with lots of files and get an HTTP error 500 because
|
||||
# of that
|
||||
###
|
||||
#LimitMEMLOCK=infinity
|
||||
#LimitNOFILE=65535
|
||||
Type=simple
|
||||
User=root
|
||||
Group=root
|
||||
WorkingDirectory={$SERVER_PATH}/nezha/agent/
|
||||
ExecStart={$SERVER_PATH}/nezha/agent/nezha-agent -s {$APP_HOST} -p {$APP_SECRET}
|
||||
Restart=always
|
||||
#Environment=DEBUG=true
|
||||
|
||||
# Some distributions may not support these hardening directives. If you cannot start the service due
|
||||
# to an unknown option, comment out the ones not supported by your version of systemd.
|
||||
#ProtectSystem=full
|
||||
#PrivateDevices=yes
|
||||
#PrivateTmp=yes
|
||||
#NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description: Nezha Agent Service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: Nezha Agent
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts Nezha Agent
|
||||
# Description: starts the Nezha Agent
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
|
||||
if [ -f /etc/init.d/functions ];then
|
||||
. /etc/init.d/functions
|
||||
fi
|
||||
|
||||
if [ -f /etc/rc.d/init.d/functions ];then
|
||||
. /etc/rc.d/init.d/functions
|
||||
fi
|
||||
|
||||
SERVICENAME=nezha-agent
|
||||
LOG_PATH={$SERVER_PATH}/nezha/logs
|
||||
APP_PATH={$SERVER_PATH}/nezha/agent
|
||||
APP_HOST={$APP_HOST}
|
||||
APP_SECRET={$APP_SECRET}
|
||||
|
||||
|
||||
app_start(){
|
||||
isStart=`ps -ef|grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting ${SERVICENAME}... \c"
|
||||
cd $APP_PATH
|
||||
exec nohup ${APP_PATH}/${SERVICENAME} -d -s ${APP_HOST} -p ${APP_SECRET} >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
echo -e ".\c"
|
||||
sleep 0.5
|
||||
isStart=$(ps -ef|grep "${SERVICENAME}" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
|
||||
let n+=1
|
||||
if [ $n -gt 15 ];then
|
||||
break;
|
||||
fi
|
||||
done
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mError: ${SERVICENAME} service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting ${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
app_stop(){
|
||||
pids=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
|
||||
arr=($pids)
|
||||
echo -e "Stopping ${SERVICENAME}... \c"
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
# echo "$p"
|
||||
kill -9 $p
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
app_status(){
|
||||
isStart=`ps -ef | grep "${SERVICENAME}" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "${SERVICENAME} not running"
|
||||
else
|
||||
echo -e "${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start') app_start;;
|
||||
'stop') app_stop;;
|
||||
'status') app_status;;
|
||||
'reload')
|
||||
app_stop
|
||||
app_start;;
|
||||
'restart')
|
||||
app_stop
|
||||
app_start;;
|
||||
esac
|
||||
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Nezha Dashborad
|
||||
After=syslog.target
|
||||
After=network.target
|
||||
After=mariadb.service mysqld.service postgresql.service memcached.service redis.service
|
||||
|
||||
[Service]
|
||||
# Modify these two values and uncomment them if you have
|
||||
# repos with lots of files and get an HTTP error 500 because
|
||||
# of that
|
||||
###
|
||||
#LimitMEMLOCK=infinity
|
||||
#LimitNOFILE=65535
|
||||
Type=simple
|
||||
#User=root
|
||||
#Group=root
|
||||
WorkingDirectory={$SERVER_PATH}/nezha/dashboard/
|
||||
ExecStart={$SERVER_PATH}/nezha/dashboard/nezha web
|
||||
Restart=always
|
||||
#Environment=DEBUG=true
|
||||
|
||||
# Some distributions may not support these hardening directives. If you cannot start the service due
|
||||
# to an unknown option, comment out the ones not supported by your version of systemd.
|
||||
ProtectSystem=full
|
||||
PrivateDevices=yes
|
||||
PrivateTmp=yes
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/bin/bash
|
||||
# chkconfig: 2345 55 25
|
||||
# description: Nezha Service
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: Nezha
|
||||
# Required-Start: $all
|
||||
# Required-Stop: $all
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: starts Nezha
|
||||
# Description: starts the Nezha
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
|
||||
if [ -f /etc/init.d/functions ];then
|
||||
. /etc/init.d/functions
|
||||
fi
|
||||
|
||||
if [ -f /etc/rc.d/init.d/functions ];then
|
||||
. /etc/rc.d/init.d/functions
|
||||
fi
|
||||
|
||||
SERVICENAME=nezha
|
||||
LOG_PATH={$SERVER_PATH}/${SERVICENAME}/logs
|
||||
APP_PATH={$SERVER_PATH}/${SERVICENAME}/dashboard
|
||||
|
||||
|
||||
app_start(){
|
||||
isStart=`ps -ef|grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "Starting ${SERVICENAME}... \c"
|
||||
cd $APP_PATH && exec nohup ${APP_PATH}/${SERVICENAME} web >> ${LOG_PATH}/${SERVICENAME}.log 2>&1 &
|
||||
isStart=""
|
||||
while [[ "$isStart" == "" ]];
|
||||
do
|
||||
echo -e ".\c"
|
||||
sleep 0.5
|
||||
isStart=$(ps -ef|grep "${SERVICENAME} web" |grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}')
|
||||
let n+=1
|
||||
if [ $n -gt 15 ];then
|
||||
break;
|
||||
fi
|
||||
done
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "\033[31mError: ${SERVICENAME} service startup failed.\033[0m"
|
||||
return;
|
||||
fi
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
else
|
||||
echo "Starting ${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
app_stop(){
|
||||
pids=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" |awk '{print $2}'`
|
||||
arr=($pids)
|
||||
echo -e "Stopping ${SERVICENAME}... \c"
|
||||
for p in ${arr[@]}
|
||||
do
|
||||
# echo "$p"
|
||||
kill -9 $p
|
||||
done
|
||||
echo -e "\033[32mdone\033[0m"
|
||||
}
|
||||
|
||||
app_status(){
|
||||
isStart=`ps -ef | grep "${SERVICENAME} web" | grep -v grep | grep -v python | grep -v "/bin/bash" | awk '{print $2}'`
|
||||
if [ "$isStart" == '' ];then
|
||||
echo -e "${SERVICENAME} not running"
|
||||
else
|
||||
echo -e "${SERVICENAME}(pid $(echo $isStart)) already running"
|
||||
fi
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
'start') app_start;;
|
||||
'stop') app_stop;;
|
||||
'status') app_status;;
|
||||
'reload')
|
||||
app_stop
|
||||
app_start;;
|
||||
'restart')
|
||||
app_stop
|
||||
app_start;;
|
||||
esac
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
action=$1
|
||||
type=$2
|
||||
|
||||
if [ "${2}" == "" ];then
|
||||
echo '缺少安装脚本...' > $install_tmp
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ ! -d $curPath/versions/$2 ];then
|
||||
echo '缺少安装脚本2...' > $install_tmp
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sh -x $curPath/versions/$2/install.sh $1
|
||||
|
||||
if [ "${action}" == "uninstall" ];then
|
||||
if [ -f /usr/lib/systemd/system/nezha.service ] || [ -f /lib/systemd/system/nezha.service ] ;then
|
||||
systemctl stop nezha
|
||||
systemctl disable nezha
|
||||
rm -rf /usr/lib/systemd/system/nezha.service
|
||||
rm -rf /lib/systemd/system/nezha.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
if [ -f /usr/lib/systemd/system/nezha-agent.service ] || [ -f /lib/systemd/system/nezha-agent.service ] ;then
|
||||
systemctl stop nezha-agent
|
||||
systemctl disable nezha-agent
|
||||
rm -rf /usr/lib/systemd/system/nezha-agent.service
|
||||
rm -rf /lib/systemd/system/nezha-agent.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
fi
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
var nezha = {
|
||||
plugin_name: 'nezha',
|
||||
init: function () {
|
||||
var _this = this;
|
||||
},
|
||||
|
||||
send:function(info){
|
||||
var tips = info['tips'];
|
||||
var method = info['method'];
|
||||
var args = info['data'];
|
||||
var callback = info['success'];
|
||||
|
||||
var loadT = layer.msg(tips, { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var data = {};
|
||||
data['name'] = 'nezha';
|
||||
data['func'] = method;
|
||||
data['version'] = $('.plugin_version').attr('version');
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/run', data, function(res) {
|
||||
layer.close(loadT);
|
||||
if (!res.status){
|
||||
layer.msg(res.msg,{icon:2,time:10000});
|
||||
return;
|
||||
}
|
||||
|
||||
var ret_data = $.parseJSON(res.data);
|
||||
console.log("send:",ret_data);
|
||||
// if (!ret_data.status){
|
||||
// layer.msg(ret_data.msg,{icon:2,time:2000});
|
||||
// return;
|
||||
// }
|
||||
|
||||
// console.log("send2:",ret_data);
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(ret_data);
|
||||
}
|
||||
},'json');
|
||||
},
|
||||
|
||||
postCallback:function(info){
|
||||
var tips = info['tips'];
|
||||
var method = info['method'];
|
||||
var args = info['data'];
|
||||
var callback = info['success'];
|
||||
|
||||
var loadT = layer.msg(tips, { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var data = {};
|
||||
data['name'] = 'nezha';
|
||||
data['func'] = method;
|
||||
data['version'] = $('.plugin_version').attr('version');
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', data, function(res) {
|
||||
layer.close(loadT);
|
||||
if (!res.status){
|
||||
layer.msg(res.msg,{icon:2,time:10000});
|
||||
return;
|
||||
}
|
||||
|
||||
var ret_data = $.parseJSON(res.data);
|
||||
if (!ret_data.status){
|
||||
layer.msg(ret_data.msg,{icon:2,time:2000});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(res);
|
||||
}
|
||||
},'json');
|
||||
},
|
||||
|
||||
repeatPwd:function (a, id) {
|
||||
$("#"+id).val(randomStrPwd(a))
|
||||
},
|
||||
|
||||
save_cfg:function(version){
|
||||
var username = $("input[name='username']").val();
|
||||
var password = $("input[name='password']").val();
|
||||
|
||||
this.send({
|
||||
tips:'正在设置中...',
|
||||
data:{'username':username,'password':password},
|
||||
method:'nezha_save_cfg',
|
||||
success:function(rdata){
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
cfg:function(version){
|
||||
this.send({
|
||||
tips:'正在获取中...',
|
||||
method:'nezha_cfg',
|
||||
success:function(data){
|
||||
var d = data.data;
|
||||
var value = '<p>\
|
||||
<span>用户名</span>\
|
||||
<input id="nz_username" style="width: 160px;" class="bt-input-text mr5" name="username" value="'+d['username']+'" type="text">\
|
||||
,<span title="随机用户名" class="glyphicon glyphicon-repeat cursor" onclick="nezha.repeatPwd(8,\'nz_username\')"></span>\
|
||||
</p>';
|
||||
|
||||
value += '<p>\
|
||||
<span>密码</span>\
|
||||
<input id="nz_password" style="width: 160px;" class="bt-input-text mr5" name="password" value="'+d['password']+'" type="text">\
|
||||
,<span title="随机密码" class="glyphicon glyphicon-repeat cursor" onclick="nezha.repeatPwd(16,\'nz_password\')"></span>\
|
||||
</p>';
|
||||
var conf = '<style>.conf_p p{margin-bottom: 2px;} .conf_p span {width: 50px;}</style><div class="conf_p" style="margin-bottom:0">\
|
||||
' + value + '\
|
||||
<div style="margin-top:10px; padding-right:15px" class="text-right">\
|
||||
<button class="btn btn-success btn-sm mr5" onclick="nezha.cfg(\'' + version + '\')">刷新</button>\
|
||||
<button class="btn btn-success btn-sm" onclick="nezha.save_cfg(\'' + version + '\')">保存</button>\
|
||||
</div>\
|
||||
</div>'
|
||||
$(".soft-man-con").html(conf);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
agent_save_cfg:function(version){
|
||||
var host = $("input[name='host']").val();
|
||||
var secret = $("input[name='secret']").val();
|
||||
|
||||
this.send({
|
||||
tips:'正在设置中...',
|
||||
data:{'host':host,'secret':secret},
|
||||
method:'agent_save_cfg',
|
||||
success:function(rdata){
|
||||
layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
agent_cfg:function(version){
|
||||
this.send({
|
||||
tips:'正在获取中...',
|
||||
method:'agent_cfg',
|
||||
success:function(data){
|
||||
var d = data.data;
|
||||
var value = '<p>\
|
||||
<span>地址</span>\
|
||||
<input id="nz_username" style="width: 160px;" class="bt-input-text mr5" name="host" value="'+d['host']+'" type="text">\
|
||||
,<font>如1.1.1.1:5444</font>\
|
||||
</p>';
|
||||
|
||||
value += '<p>\
|
||||
<span>密钥</span>\
|
||||
<input id="nz_password" style="width: 160px;" class="bt-input-text mr5" name="secret" value="'+d['secret']+'" type="text">\
|
||||
,<font>密钥</font>\
|
||||
</p>';
|
||||
var conf = '<style>.conf_p p{margin-bottom: 2px;} .conf_p span {width: 50px;}</style><div class="conf_p" style="margin-bottom:0">\
|
||||
' + value + '\
|
||||
<div style="margin-top:10px; padding-right:15px" class="text-right">\
|
||||
<button class="btn btn-success btn-sm mr5" onclick="nezha.agent_cfg(\'' + version + '\')">刷新</button>\
|
||||
<button class="btn btn-success btn-sm" onclick="nezha.agent_save_cfg(\'' + version + '\')">保存</button>\
|
||||
</div>\
|
||||
</div>'
|
||||
$(".soft-man-con").html(conf);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
readme:function (){
|
||||
var readme = '<ul class="help-info-text c7">';
|
||||
readme += '<li>安装时不会自动启动。</li>';
|
||||
readme += '<li>哪吒面板是改造版,用户名和密码登录【面板配置】,不依赖github/gitee/gitlab。</li>';
|
||||
readme += '<li>Agent需要先手动填写正确信息。</li>';
|
||||
readme += '</ul>';
|
||||
$('.soft-man-con').html(readme);
|
||||
}
|
||||
}
|
||||
Executable
+158
@@ -0,0 +1,158 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
VERSION=0.15.2
|
||||
|
||||
# bash install.sh install 0.15.2
|
||||
# cd /www/server/mdserver-web/plugins/nezha && bash install.sh install 0.15.2
|
||||
# cd /Users/midoks/Desktop/mwdev/server/mdserver-web/plugins/nezha && bash install.sh install 0.15.2
|
||||
|
||||
bash ${rootPath}/scripts/getos.sh
|
||||
OSNAME=`cat ${rootPath}/data/osname.pl`
|
||||
OSNAME_ID=`cat /etc/*-release | grep VERSION_ID | awk -F = '{print $2}' | awk -F "\"" '{print $2}'`
|
||||
|
||||
|
||||
ARCH="amd64"
|
||||
|
||||
get_arch() {
|
||||
TMP_ARCH=`arch`
|
||||
if [ "$TMP_ARCH" == "x86_64" ];then
|
||||
ARCH="amd64"
|
||||
elif [ "$TMP_ARCH" == "aarch64" ];then
|
||||
ARCH="arm64"
|
||||
else
|
||||
echo $ARCH
|
||||
fi
|
||||
}
|
||||
|
||||
load_vars() {
|
||||
OS=$(uname | tr '[:upper:]' '[:lower:]')
|
||||
TARGET_DIR="$serverPath/nezha/dashboard"
|
||||
|
||||
|
||||
## China_IP
|
||||
if [[ -z "${CN}" ]]; then
|
||||
if [[ $(curl -m 10 -s https://ipapi.co/json | grep 'China') != "" ]]; then
|
||||
CN=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${CN}" ]]; then
|
||||
GITHUB_RAW_URL="raw.githubusercontent.com/midoks/nezha/main"
|
||||
GITHUB_URL="github.com"
|
||||
else
|
||||
GITHUB_RAW_URL="cdn.jsdelivr.net/gh/midoks/nezha@main"
|
||||
GITHUB_URL="dn-dao-github-mirror.daocloud.io"
|
||||
fi
|
||||
|
||||
echo $GITHUB_RAW_URL
|
||||
echo $GITHUB_URL
|
||||
}
|
||||
|
||||
# download file
|
||||
download_file() {
|
||||
url="${1}"
|
||||
destination="${2}"
|
||||
|
||||
printf "Fetching ${url} \n\n"
|
||||
|
||||
if test -x "$(command -v curl)"; then
|
||||
code=$(curl --connect-timeout 15 -w '%{http_code}' -L "${url}" -o "${destination}")
|
||||
elif test -x "$(command -v wget)"; then
|
||||
code=$(wget -t2 -T15 -O "${destination}" --server-response "${url}" 2>&1 | awk '/^ HTTP/{print $2}' | tail -1)
|
||||
else
|
||||
printf "\e[1;31mNeither curl nor wget was available to perform http requests.\e[0m\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "${code}" != 200 ]; then
|
||||
printf "\e[1;31mRequest failed with code %s\e[0m\n" $code
|
||||
exit 1
|
||||
else
|
||||
printf "\n\e[1;33mDownload succeeded\e[0m\n"
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
Install_dashborad(){
|
||||
echo '正在安装哪吒监控...' > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
if [ ! -f $TARGET_DIR/nezha ];then
|
||||
|
||||
DOWNLOAD_URL="https://${GITHUB_URL}/midoks/nezha/releases/download/v${VERSION}/nezha-${OS}-${ARCH}.zip"
|
||||
|
||||
DOWNLOAD_FILE="$(mktemp).zip"
|
||||
download_file $DOWNLOAD_URL $DOWNLOAD_FILE
|
||||
|
||||
if [ ! -d $TARGET_DIR ]; then
|
||||
mkdir -p $TARGET_DIR
|
||||
fi
|
||||
|
||||
unzip $DOWNLOAD_FILE -d $TARGET_DIR
|
||||
rm -rf $DOWNLOAD_FILE
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
Install_agent(){
|
||||
echo -e "正在下载监控端" > $install_tmp
|
||||
mkdir -p $serverPath/source
|
||||
|
||||
version=v0.15.1
|
||||
|
||||
AGENT_TARGET_DIR="$serverPath/nezha/agent"
|
||||
|
||||
DOWNLOAD_URL="https://${GITHUB_URL}/nezhahq/agent/releases/download/${version}/nezha-agent_${OS}_${ARCH}.zip"
|
||||
DOWNLOAD_FILE="$(mktemp).zip"
|
||||
|
||||
if [ ! -f $AGENT_TARGET_DIR/nezha-agent ];then
|
||||
download_file $DOWNLOAD_URL $DOWNLOAD_FILE
|
||||
|
||||
if [ ! -d $AGENT_TARGET_DIR ]; then
|
||||
mkdir -p $AGENT_TARGET_DIR
|
||||
fi
|
||||
|
||||
unzip $DOWNLOAD_FILE -d $AGENT_TARGET_DIR
|
||||
rm -rf $DOWNLOAD_FILE
|
||||
fi
|
||||
}
|
||||
|
||||
Install_App()
|
||||
{
|
||||
load_vars
|
||||
get_arch
|
||||
|
||||
Install_dashborad
|
||||
Install_agent
|
||||
|
||||
if [ -d $serverPath/nezha ];then
|
||||
echo "$VERSION" > $serverPath/nezha/version.pl
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py init_cfg
|
||||
fi
|
||||
echo 'install successful' > $install_tmp
|
||||
}
|
||||
|
||||
Uninstall_App()
|
||||
{
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py initd_uninstall
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py initd_uninstall_agent
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py stop
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/nezha/index.py stop_agent
|
||||
rm -rf $serverPath/nezha
|
||||
echo "install fail" > $install_tmp
|
||||
}
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,2 @@
|
||||
## 指定共享内存
|
||||
lua_shared_dict healthcheck 10m;
|
||||
@@ -0,0 +1,64 @@
|
||||
location / {
|
||||
proxy_pass http://{$UPSTREAM_NAME};
|
||||
|
||||
client_max_body_size 10m;
|
||||
client_body_buffer_size 128k;
|
||||
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header Host $proxy_host;
|
||||
proxy_connect_timeout 90;
|
||||
proxy_send_timeout 90;
|
||||
proxy_read_timeout 90;
|
||||
proxy_buffer_size 4k;
|
||||
proxy_buffers 4 32k;
|
||||
proxy_busy_buffers_size 64k;
|
||||
proxy_temp_file_write_size 64k;
|
||||
}
|
||||
|
||||
|
||||
#location /upstream_status {
|
||||
# allow 127.0.0.1;
|
||||
# deny all;
|
||||
# access_log off;
|
||||
# default_type text/plain;
|
||||
# content_by_lua_block {
|
||||
# local hc = require "resty.upstream.healthcheck"
|
||||
# ngx.say("OpenResty Worker PID: ", ngx.worker.pid())
|
||||
# ngx.print(hc.status_page())
|
||||
# }
|
||||
#}
|
||||
|
||||
location /upstream_status_{$UPSTREAM_NAME} {
|
||||
allow 127.0.0.1;
|
||||
deny all;
|
||||
access_log off;
|
||||
default_type text/plain;
|
||||
content_by_lua_block {
|
||||
local json = require "cjson"
|
||||
local ok, upstream = pcall(require, "ngx.upstream")
|
||||
if not ok then
|
||||
ngx.print("[]")
|
||||
return
|
||||
end
|
||||
|
||||
local get_primary_peers = upstream.get_primary_peers
|
||||
local get_backup_peers = upstream.get_backup_peers
|
||||
local upstream_name = "{$UPSTREAM_NAME}"
|
||||
|
||||
peers, err = get_primary_peers(upstream_name)
|
||||
if not peers then
|
||||
ngx.print("[]")
|
||||
return
|
||||
end
|
||||
|
||||
peers_backup, err = get_backup_peers(upstream_name)
|
||||
if peers_backup then
|
||||
for k, v in pairs(peers_backup) do
|
||||
table.insert(peers,v)
|
||||
end
|
||||
end
|
||||
|
||||
ngx.print(json.encode(peers))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
upstream {$UPSTREAM_NAME}
|
||||
{
|
||||
{$NODE_ALGO}
|
||||
{$NODE_SERVER_LIST}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 853 B |
Executable
+21
@@ -0,0 +1,21 @@
|
||||
<div class="bt-form">
|
||||
<div class="bt-w-main">
|
||||
<div class="bt-w-menu">
|
||||
<p class="bgw" onclick="pluginService('op_load_balance');">服务</p>
|
||||
<p onclick="loadBalanceList();">负载均衡</p>
|
||||
</div>
|
||||
<div class="bt-w-con pd15">
|
||||
<div class="soft-man-con"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script type="text/javascript" src="/plugins/file?name=op_load_balance&f=js/app.js"></script>
|
||||
<script type="text/javascript">
|
||||
resetPluginWinWidth(800);
|
||||
resetPluginWinHeight(300);
|
||||
$.getScript( "/plugins/file?name=op_load_balance&f=js/app.js", function(){
|
||||
pluginService('op_load_balance');
|
||||
});
|
||||
</script>
|
||||
Executable
+474
@@ -0,0 +1,474 @@
|
||||
# coding:utf-8
|
||||
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import subprocess
|
||||
import json
|
||||
import re
|
||||
|
||||
sys.path.append(os.getcwd() + "/class/core")
|
||||
import mw
|
||||
|
||||
|
||||
app_debug = False
|
||||
if mw.isAppleSystem():
|
||||
app_debug = True
|
||||
|
||||
|
||||
def getPluginName():
|
||||
return 'op_load_balance'
|
||||
|
||||
|
||||
def getPluginDir():
|
||||
return mw.getPluginDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getServerDir():
|
||||
return mw.getServerDir() + '/' + getPluginName()
|
||||
|
||||
|
||||
def getArgs():
|
||||
args = sys.argv[2:]
|
||||
tmp = {}
|
||||
args_len = len(args)
|
||||
|
||||
if args_len == 1:
|
||||
t = args[0].strip('{').strip('}')
|
||||
if t.strip() == '':
|
||||
tmp = []
|
||||
else:
|
||||
t = t.split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
tmp[t[0]] = t[1]
|
||||
elif args_len > 1:
|
||||
for i in range(len(args)):
|
||||
t = args[i].split(':')
|
||||
tmp[t[0]] = t[1]
|
||||
return tmp
|
||||
|
||||
|
||||
def checkArgs(data, ck=[]):
|
||||
for i in range(len(ck)):
|
||||
if not ck[i] in data:
|
||||
return (False, mw.returnJson(False, '参数:(' + ck[i] + ')没有!'))
|
||||
return (True, mw.returnJson(True, 'ok'))
|
||||
|
||||
|
||||
def getConf():
|
||||
path = getServerDir() + "/cfg.json"
|
||||
|
||||
if not os.path.exists(path):
|
||||
mw.writeFile(path, '[]')
|
||||
|
||||
c = mw.readFile(path)
|
||||
return json.loads(c)
|
||||
|
||||
|
||||
def writeConf(data):
|
||||
path = getServerDir() + "/cfg.json"
|
||||
mw.writeFile(path, json.dumps(data))
|
||||
|
||||
|
||||
def contentReplace(content):
|
||||
service_path = mw.getServerDir()
|
||||
content = content.replace('{$ROOT_PATH}', mw.getRootDir())
|
||||
content = content.replace('{$SERVER_PATH}', service_path)
|
||||
content = content.replace('{$APP_PATH}', app_path)
|
||||
return content
|
||||
|
||||
|
||||
def restartWeb():
|
||||
mw.opWeb('stop')
|
||||
mw.opWeb('start')
|
||||
|
||||
|
||||
def loadBalanceConf():
|
||||
path = mw.getServerDir() + '/web_conf/nginx/vhost/load_balance.conf'
|
||||
return path
|
||||
|
||||
|
||||
def initDreplace():
|
||||
|
||||
dst_conf_tpl = getPluginDir() + '/conf/load_balance.conf'
|
||||
dst_conf = loadBalanceConf()
|
||||
|
||||
if not os.path.exists(dst_conf):
|
||||
con = mw.readFile(dst_conf_tpl)
|
||||
mw.writeFile(dst_conf, con)
|
||||
|
||||
|
||||
def status():
|
||||
if not mw.getWebStatus():
|
||||
return 'stop'
|
||||
|
||||
dst_conf = loadBalanceConf()
|
||||
if not os.path.exists(dst_conf):
|
||||
return 'stop'
|
||||
|
||||
return 'start'
|
||||
|
||||
|
||||
def start():
|
||||
initDreplace()
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def stop():
|
||||
dst_conf = loadBalanceConf()
|
||||
os.remove(dst_conf)
|
||||
|
||||
deleteLoadBalanceAllCfg()
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def restart():
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def reload():
|
||||
restartWeb()
|
||||
return 'ok'
|
||||
|
||||
|
||||
def installPreInspection():
|
||||
check_op = mw.getServerDir() + "/openresty"
|
||||
if not os.path.exists(check_op):
|
||||
return "请先安装OpenResty"
|
||||
return 'ok'
|
||||
|
||||
|
||||
def deleteLoadBalanceAllCfg():
|
||||
cfg = getConf()
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
lua_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
|
||||
|
||||
for conf in cfg:
|
||||
upstream_file = upstream_dir + '/' + conf['upstream_name'] + '.conf'
|
||||
if os.path.exists(upstream_file):
|
||||
os.remove(upstream_file)
|
||||
|
||||
lua_file = lua_dir + '/' + conf['upstream_name'] + '.lua'
|
||||
if os.path.exists(lua_file):
|
||||
os.remove(lua_file)
|
||||
|
||||
rewrite_file = rewrite_dir + '/' + conf['domain'] + '.conf'
|
||||
mw.writeFile(rewrite_file, '')
|
||||
|
||||
path = vhost_dir + '/' + conf['domain'] + '.conf'
|
||||
|
||||
content = mw.readFile(path)
|
||||
content = re.sub('include ' + upstream_file + ';' + "\n", '', content)
|
||||
mw.writeFile(path, content)
|
||||
|
||||
mw.opLuaInitWorkerFile()
|
||||
|
||||
|
||||
def makeConfServerList(data):
|
||||
slist = ''
|
||||
for x in data:
|
||||
slist += 'server '
|
||||
slist += x['ip'] + ':' + x['port']
|
||||
|
||||
if x['state'] == '0':
|
||||
slist += ' down;\n\t'
|
||||
continue
|
||||
|
||||
if x['state'] == '2':
|
||||
slist += ' backup;\n\t'
|
||||
continue
|
||||
|
||||
slist += ' weight=' + x['weight']
|
||||
slist += ' max_fails=' + x['max_fails']
|
||||
slist += ' fail_timeout=' + x['fail_timeout'] + "s;\n\t"
|
||||
return slist
|
||||
|
||||
|
||||
def makeLoadBalanceAllCfg(row):
|
||||
# 生成所有配置
|
||||
cfg = getConf()
|
||||
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
|
||||
upstream_tpl = getPluginDir() + '/conf/upstream.tpl.conf'
|
||||
rewrite_tpl = getPluginDir() + '/conf/rewrite.tpl.conf'
|
||||
|
||||
if not os.path.exists(upstream_dir):
|
||||
os.makedirs(upstream_dir)
|
||||
|
||||
conf = cfg[row]
|
||||
|
||||
# replace vhost start
|
||||
vhost_file = vhost_dir + '/' + conf['domain'] + '.conf'
|
||||
vcontent = mw.readFile(vhost_file)
|
||||
|
||||
vhost_find_str = 'upstream/' + conf['upstream_name'] + '.conf'
|
||||
vhead = 'include ' + mw.getServerDir() + '/web_conf/nginx/' + \
|
||||
vhost_find_str + ';'
|
||||
|
||||
vpos = vcontent.find(vhost_find_str)
|
||||
if vpos < 0:
|
||||
vcontent = vhead + "\n" + vcontent
|
||||
mw.writeFile(vhost_file, vcontent)
|
||||
# replace vhost end
|
||||
|
||||
# make upstream start
|
||||
upstream_file = upstream_dir + '/' + conf['upstream_name'] + '.conf'
|
||||
content = ''
|
||||
if len(conf['node_list']) > 0:
|
||||
content = mw.readFile(upstream_tpl)
|
||||
slist = makeConfServerList(conf['node_list'])
|
||||
content = content.replace('{$NODE_SERVER_LIST}', slist)
|
||||
content = content.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
if conf['node_algo'] != 'polling':
|
||||
content = content.replace('{$NODE_ALGO}', conf['node_algo'] + ';')
|
||||
else:
|
||||
content = content.replace('{$NODE_ALGO}', '')
|
||||
mw.writeFile(upstream_file, content)
|
||||
# make upstream end
|
||||
|
||||
# make rewrite start
|
||||
rewrite_file = rewrite_dir + '/' + conf['domain'] + '.conf'
|
||||
rcontent = ''
|
||||
if len(conf['node_list']) > 0:
|
||||
rcontent = mw.readFile(rewrite_tpl)
|
||||
rcontent = rcontent.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
mw.writeFile(rewrite_file, rcontent)
|
||||
# make rewrite end
|
||||
|
||||
# health check start
|
||||
lua_dir = mw.getServerDir() + '/web_conf/nginx/lua/init_worker_by_lua_file'
|
||||
lua_init_worker_file = lua_dir + '/' + conf['upstream_name'] + '.lua'
|
||||
if conf['node_health_check'] == 'ok':
|
||||
lua_dir_tpl = getPluginDir() + '/lua/health_check.lua.tpl'
|
||||
content = mw.readFile(lua_dir_tpl)
|
||||
content = content.replace('{$UPSTREAM_NAME}', conf['upstream_name'])
|
||||
content = content.replace('{$DOMAIN}', conf['domain'])
|
||||
mw.writeFile(lua_init_worker_file, content)
|
||||
else:
|
||||
if os.path.exists(lua_init_worker_file):
|
||||
os.remove(lua_init_worker_file)
|
||||
|
||||
mw.opLuaInitWorkerFile()
|
||||
# health check end
|
||||
return True
|
||||
|
||||
|
||||
def add_load_balance(args):
|
||||
|
||||
data = checkArgs(
|
||||
args, ['domain', 'upstream_name', 'node_algo', 'node_list', 'node_health_check'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
domain_json = args['domain']
|
||||
|
||||
tmp = json.loads(domain_json)
|
||||
domain = tmp['domain']
|
||||
|
||||
cfg = getConf()
|
||||
cfg_len = len(cfg)
|
||||
tmp = {}
|
||||
tmp['domain'] = domain
|
||||
tmp['data'] = args['domain']
|
||||
tmp['upstream_name'] = args['upstream_name']
|
||||
tmp['node_algo'] = args['node_algo']
|
||||
tmp['node_list'] = args['node_list']
|
||||
tmp['node_health_check'] = args['node_health_check']
|
||||
cfg.append(tmp)
|
||||
writeConf(cfg)
|
||||
|
||||
import site_api
|
||||
sobj = site_api.site_api()
|
||||
domain_path = mw.getWwwDir() + '/' + domain
|
||||
|
||||
ps = '负载均衡[' + domain + ']'
|
||||
data = sobj.add(domain_json, '80', ps, domain_path, '00')
|
||||
|
||||
makeLoadBalanceAllCfg(cfg_len)
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, '添加成功', data)
|
||||
|
||||
|
||||
def edit_load_balance(args):
|
||||
data = checkArgs(
|
||||
args, ['row', 'node_algo', 'node_list', 'node_health_check'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
tmp = cfg[row]
|
||||
tmp['node_algo'] = args['node_algo']
|
||||
tmp['node_list'] = args['node_list']
|
||||
tmp['node_health_check'] = args['node_health_check']
|
||||
cfg[row] = tmp
|
||||
writeConf(cfg)
|
||||
|
||||
makeLoadBalanceAllCfg(row)
|
||||
mw.restartWeb()
|
||||
return mw.returnJson(True, '修改成功', data)
|
||||
|
||||
|
||||
def loadBalanceList():
|
||||
cfg = getConf()
|
||||
return mw.returnJson(True, 'ok', cfg)
|
||||
|
||||
|
||||
def loadBalanceDelete():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['row'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
data = cfg[row]
|
||||
|
||||
import site_api
|
||||
sobj = site_api.site_api()
|
||||
|
||||
sid = mw.M('sites').where('name=?', (data['domain'],)).getField('id')
|
||||
|
||||
if type(sid) == list:
|
||||
del(cfg[row])
|
||||
writeConf(cfg)
|
||||
return mw.returnJson(False, '已经删除了!')
|
||||
|
||||
status = sobj.delete(sid, data['domain'], 1)
|
||||
status_data = json.loads(status)
|
||||
|
||||
if status_data['status']:
|
||||
del(cfg[row])
|
||||
writeConf(cfg)
|
||||
|
||||
upstream_dir = mw.getServerDir() + '/web_conf/nginx/upstream'
|
||||
rewrite_dir = mw.getServerDir() + '/web_conf/nginx/rewrite'
|
||||
|
||||
upstream_file = upstream_dir + '/' + data['upstream_name'] + '.conf'
|
||||
if os.path.exists(upstream_file):
|
||||
os.remove(upstream_file)
|
||||
|
||||
rewrite_file = rewrite_dir + '/' + data['domain'] + '.conf'
|
||||
if os.path.exists(rewrite_file):
|
||||
mw.writeFile(rewrite_file, '')
|
||||
|
||||
return mw.returnJson(status_data['status'], status_data['msg'])
|
||||
|
||||
|
||||
def http_get(url):
|
||||
ret = re.search(r'https://', url)
|
||||
if ret:
|
||||
try:
|
||||
from gevent import monkey
|
||||
monkey.patch_ssl()
|
||||
import requests
|
||||
ret = requests.get(url=str(url), verify=False, timeout=10)
|
||||
status = [200, 301, 302, 404, 403]
|
||||
if ret.status_code in status:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
if sys.version_info[0] == 2:
|
||||
import urllib2
|
||||
rec = urllib2.urlopen(url, timeout=3)
|
||||
else:
|
||||
import urllib.request
|
||||
rec = urllib.request.urlopen(url, timeout=3)
|
||||
status = [200, 301, 302, 404, 403]
|
||||
if rec.getcode() in status:
|
||||
return True
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def checkUrl():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['ip', 'port', 'path'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
ip = args['ip']
|
||||
port = args['port']
|
||||
path = args['path']
|
||||
|
||||
if port == '443':
|
||||
url = 'https://' + str(ip) + ':' + str(port) + str(path.strip())
|
||||
else:
|
||||
url = 'http://' + str(ip) + ':' + str(port) + str(path.strip())
|
||||
ret = http_get(url)
|
||||
if not ret:
|
||||
return mw.returnJson(False, '访问节点[%s]失败' % url)
|
||||
return mw.returnJson(True, '访问节点[%s]成功' % url)
|
||||
|
||||
|
||||
def getHealthStatus():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['row'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
row = int(args['row'])
|
||||
|
||||
cfg = getConf()
|
||||
data = cfg[row]
|
||||
|
||||
url = 'http://' + data['domain'] + \
|
||||
'/upstream_status_' + data['upstream_name']
|
||||
|
||||
url_data = mw.httpGet(url)
|
||||
return mw.returnJson(True, 'ok', json.loads(url_data))
|
||||
|
||||
|
||||
def getLogs():
|
||||
args = getArgs()
|
||||
data = checkArgs(args, ['domain'])
|
||||
if not data[0]:
|
||||
return data[1]
|
||||
|
||||
domain = args['domain']
|
||||
logs = mw.getLogsDir() + '/' + domain + '.log'
|
||||
return logs
|
||||
|
||||
if __name__ == "__main__":
|
||||
func = sys.argv[1]
|
||||
if func == 'status':
|
||||
print(status())
|
||||
elif func == 'start':
|
||||
print(start())
|
||||
elif func == 'stop':
|
||||
print(stop())
|
||||
elif func == 'restart':
|
||||
print(restart())
|
||||
elif func == 'reload':
|
||||
print(reload())
|
||||
elif func == 'install_pre_inspection':
|
||||
print(installPreInspection())
|
||||
elif func == 'add_load_balance':
|
||||
print(addLoadBalance())
|
||||
elif func == 'load_balance_list':
|
||||
print(loadBalanceList())
|
||||
elif func == 'load_balance_delete':
|
||||
print(loadBalanceDelete())
|
||||
elif func == 'check_url':
|
||||
print(checkUrl())
|
||||
elif func == 'get_logs':
|
||||
print(getLogs())
|
||||
elif func == 'get_health_status':
|
||||
print(getHealthStatus())
|
||||
else:
|
||||
print('error')
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title":"OP负载均衡",
|
||||
"tip":"soft",
|
||||
"name":"op_load_balance",
|
||||
"type":"其他插件",
|
||||
"install_pre_inspection":true,
|
||||
"ps":"基于OpenResty的负载均衡",
|
||||
"shell":"install.sh",
|
||||
"checks":"server/op_load_balance",
|
||||
"path":"server/op_load_balance",
|
||||
"author":"midoks",
|
||||
"home":"https://github.com/midoks",
|
||||
"date":"2023-02-02",
|
||||
"pid": "1",
|
||||
"versions": ["1.0"]
|
||||
}
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
|
||||
export PATH
|
||||
|
||||
curPath=`pwd`
|
||||
rootPath=$(dirname "$curPath")
|
||||
rootPath=$(dirname "$rootPath")
|
||||
serverPath=$(dirname "$rootPath")
|
||||
|
||||
install_tmp=${rootPath}/tmp/mw_install.pl
|
||||
|
||||
action=$1
|
||||
version=$2
|
||||
sys_os=`uname`
|
||||
|
||||
if [ -f ${rootPath}/bin/activate ];then
|
||||
source ${rootPath}/bin/activate
|
||||
fi
|
||||
|
||||
if [ "$sys_os" == "Darwin" ];then
|
||||
BAK='_bak'
|
||||
else
|
||||
BAK=''
|
||||
fi
|
||||
|
||||
Install_App(){
|
||||
echo '正在安装脚本文件...' > $install_tmp
|
||||
mkdir -p $serverPath/op_load_balance
|
||||
echo "${version}" > $serverPath/op_load_balance/version.pl
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/op_load_balance/index.py start
|
||||
echo 'install ok' > $install_tmp
|
||||
}
|
||||
|
||||
Uninstall_App(){
|
||||
cd ${rootPath} && python3 ${rootPath}/plugins/op_load_balance/index.py stop
|
||||
rm -rf $serverPath/op_load_balance
|
||||
}
|
||||
|
||||
|
||||
action=$1
|
||||
if [ "${1}" == 'install' ];then
|
||||
Install_App
|
||||
else
|
||||
Uninstall_App
|
||||
fi
|
||||
@@ -0,0 +1,606 @@
|
||||
function ooPost(method,args,callback){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
$.post('/plugins/run', {name:'op_load_balance', func:method, args:_args}, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function ooAsyncPost(method,args){
|
||||
var _args = null;
|
||||
if (typeof(args) == 'string'){
|
||||
_args = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
_args = JSON.stringify(args);
|
||||
}
|
||||
return syncPost('/plugins/run', {name:'op_load_balance', func:method, args:_args});
|
||||
}
|
||||
|
||||
function ooPostCallbak(method, args, callback){
|
||||
var loadT = layer.msg('正在获取...', { icon: 16, time: 0, shade: 0.3 });
|
||||
|
||||
var req_data = {};
|
||||
req_data['name'] = 'op_load_balance';
|
||||
req_data['func'] = method;
|
||||
args['version'] = '1.0';
|
||||
|
||||
if (typeof(args) == 'string'){
|
||||
req_data['args'] = JSON.stringify(toArrayObject(args));
|
||||
} else {
|
||||
req_data['args'] = JSON.stringify(args);
|
||||
}
|
||||
|
||||
$.post('/plugins/callback', req_data, function(data) {
|
||||
layer.close(loadT);
|
||||
if (!data.status){
|
||||
layer.msg(data.msg,{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
if(typeof(callback) == 'function'){
|
||||
callback(data);
|
||||
}
|
||||
},'json');
|
||||
}
|
||||
|
||||
function addNode(){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['450px','580px'],
|
||||
title: '添加节点',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>IP地址</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='ip' class='bt-input-text mr5' placeholder='负载名称,可以是英文字母和下划线,不能使用中文' type='text' style='width:250px' value='127.0.0.1'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>端口</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='port' class='bt-input-text mr5' type='text' style='width:250px' value='80'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>验证文件路径</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='path' class='bt-input-text mr5' type='text' style='width:250px' value='/'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点状态</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='state'>\
|
||||
<option value='1'>参与者</option>\
|
||||
<option value='2'>备份</option>\
|
||||
<option value='0'>停用</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>权重</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='weight' class='bt-input-text mr5' type='text' style='width:250px' value='1'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>阈值</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='max_fails' class='bt-input-text mr5' type='text' style='width:250px' value='2'>次\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>恢复时间</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='fail_timeout' class='bt-input-text mr5' type='text' style='width:250px' value='10'>秒\
|
||||
</div>\
|
||||
</div>\
|
||||
<ul style='margin-left:10px' class='help-info-text c7'>\
|
||||
<li>备份状态: 指当其它节点都无法使用时才会使用此节点</li>\
|
||||
<li>参与状态: 正常参与负载均衡,请至少添加1个普通节点</li>\
|
||||
<li>验证文件路径: 用于检查文件路径地址是否可用</li>\
|
||||
<li>IP地址: 仅支持IP地址,否则无法正常参与负载均衡</li>\
|
||||
<li>阈值: 在恢复时间的时间段内,如果OpenResty与节点通信尝试失败的次数达到此值,OpenResty就认为服务器不可用</li>\
|
||||
</ul>\
|
||||
</form>",
|
||||
success:function(){
|
||||
},
|
||||
yes:function(index) {
|
||||
|
||||
var ip = $('input[name="ip"]').val();
|
||||
var port = $('input[name="port"]').val();
|
||||
var path = $('input[name="path"]').val();
|
||||
var state = $('select[name="state"]').val();
|
||||
var weight = $('input[name="weight"]').val();
|
||||
var max_fails = $('input[name="max_fails"]').val();
|
||||
var fail_timeout = $('input[name="fail_timeout"]').val();
|
||||
|
||||
ooPost('check_url', {ip:ip,port:port,path:path},function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
if (rdata.status){
|
||||
layer.close(index);
|
||||
$('#nodecon .nulltr').hide();
|
||||
|
||||
var tbody = '<tr>';
|
||||
tbody +='<td>'+ip+'</td>';
|
||||
tbody +='<td>'+port+'</td>';
|
||||
tbody +='<td>'+path+'</td>';
|
||||
|
||||
tbody +="<td><select name='state'>";
|
||||
var state_option_list = {
|
||||
'1':'参与者',
|
||||
'2':'备份',
|
||||
'0':'停用',
|
||||
}
|
||||
for (i in state_option_list) {
|
||||
if (i == state){
|
||||
tbody +="<option value='"+i+"' selected>"+state_option_list[i]+"</option>";
|
||||
} else{
|
||||
tbody +="<option value='"+i+"'>"+state_option_list[i]+"</option>";
|
||||
}
|
||||
}
|
||||
tbody +="</select></td>";
|
||||
|
||||
tbody +='<td><input type="number" name="weight" value="'+weight+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="max_fails" value="'+max_fails+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="fail_timeout" value="'+fail_timeout+'" style="width:50px"></td>';
|
||||
tbody +='<td class="text-right" width="50"><a class="btlink minus delete">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
$('#nodecon').append(tbody);
|
||||
|
||||
$('#nodecon .delete').click(function(){
|
||||
$(this).parent().parent().remove();
|
||||
if ($('#nodecon tr').length == 1 ){
|
||||
$('#nodecon .nulltr').show();
|
||||
}
|
||||
});
|
||||
}
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addBalance(){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['750px','460px'],
|
||||
title: '创建负载',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>域名</span>\
|
||||
<div class='info-r'><textarea name='load_domain' class='bt-input-text mr5' placeholder='' style='width:95%;resize: none;height:90px;line-height:20px;'></textarea></div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>负载名称</span>\
|
||||
<div class='info-r'>\
|
||||
<input name='upstream_name' class='bt-input-text mr5' placeholder='负载名称,可以是英文字母和下划线,不能使用中文' type='text' style='width:95%' value=''>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点调度</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='node_algo'>\
|
||||
<option value='polling'>轮询[默认]</option>\
|
||||
<option value='ip_hash'>ip_hash</option>\
|
||||
<option value='fair'>fair</option>\
|
||||
<option value='url_hash'>url_hash</option>\
|
||||
<option value='least_conn'>least_conn</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点健康检查</span>\
|
||||
<div class='info-r'>\
|
||||
<input type='checkbox' name='node_health_check' checked>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点</span>\
|
||||
<div class='info-r'>\
|
||||
<div class='table-con divtable' style='max-height:120px;overflow:auto; margin-bottom:8px;width:95%'>\
|
||||
<table class='table table-hover' id='fixTable3'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>IP地址</th>\
|
||||
<th width='60'>端口</th>\
|
||||
<th width='120'>验证路径</th>\
|
||||
<th width='60'>状态</th>\
|
||||
<th width='60'>权重</th>\
|
||||
<th width='60'>阀值</th>\
|
||||
<th width='120'>恢复时间</th>\
|
||||
<th width='80' class='text-right'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id='nodecon'>\
|
||||
<tr class='nulltr'>\
|
||||
<td colspan='8' align='center'>当前节点为空,请至少添加一个普通节点</td>\
|
||||
</tr>\
|
||||
</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
<span class='btn btn-success btn-sm add_node' style='vertical-align:0'>添加节点</span>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('textarea[name="load_domain"]').attr('placeholder','每行填写一个域名,默认为80端口。\n泛解析添加方法 *.domain.com\n如另加端口格式为 www.domain.com:88');
|
||||
var rval = getRandomString(6);
|
||||
$('input[name="upstream_name"]').val('load_balance_'+rval);
|
||||
|
||||
$('.add_node').click(function(){
|
||||
addNode();
|
||||
});
|
||||
},
|
||||
yes:function(index) {
|
||||
var data = {};
|
||||
|
||||
var upstream_name = $('input[name="upstream_name"]').val();
|
||||
if (upstream_name == ''){
|
||||
layer.msg('负载名称不能为空!',{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
var domain = $('textarea[name="load_domain"]').val().replace('http://','').replace('https://','').split("\n");
|
||||
if (domain[0] == ''){
|
||||
layer.msg('域名不能为空!',{icon:0,time:2000,shade: [0.3, '#000']});
|
||||
return;
|
||||
}
|
||||
|
||||
var domainlist = '';
|
||||
for(var i=1; i<domain.length; i++){
|
||||
domainlist += '"'+domain[i]+'",';
|
||||
}
|
||||
domain ='{"domain":"'+domain[0]+'","domainlist":['+domainlist+'],"count":'+domain.length+'}';//拼接json
|
||||
data['domain'] = domain;
|
||||
data['upstream_name'] = upstream_name;
|
||||
|
||||
data['node_algo'] = $('select[name="node_algo"]').val();
|
||||
|
||||
data['node_health_check'] = 'fail';
|
||||
if ($('input[name="node_health_check"]').prop('checked')){
|
||||
data['node_health_check'] = 'ok';
|
||||
}
|
||||
|
||||
var node_list = [];
|
||||
$('#nodecon tr').each(function(){
|
||||
|
||||
var ip = $(this).find('td').eq(0).text();
|
||||
var port = $(this).find('td').eq(1).text();
|
||||
|
||||
if (port == ''){return;}
|
||||
|
||||
var path = $(this).find('td').eq(2).text();
|
||||
var state = $(this).find('select[name="state"]').val();
|
||||
var weight = $(this).find('input[name="weight"]').val();
|
||||
var max_fails = $(this).find('input[name="max_fails"]').val();
|
||||
var fail_timeout = $(this).find('input[name="fail_timeout"]').val();
|
||||
|
||||
var tmp = {
|
||||
ip:ip,
|
||||
port:port,
|
||||
path:path,
|
||||
state:state,
|
||||
weight:weight,
|
||||
max_fails:max_fails,
|
||||
fail_timeout:fail_timeout,
|
||||
}
|
||||
node_list.push(tmp);
|
||||
});
|
||||
data['node_list'] = node_list;
|
||||
ooPostCallbak('add_load_balance', data, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
layer.close(index);
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function editBalance(data, row){
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['750px','400px'],
|
||||
title: '编辑负载',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content: "<form class='bt-form pd20'>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>负载名称</span>\
|
||||
<div class='info-r'><input name='upstream_name' class='bt-input-text mr5' type='text' style='width:95%;background: rgb(238, 238, 238);' value='' readonly></div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点调度</span>\
|
||||
<div class='info-r'>\
|
||||
<select name='node_algo'>\
|
||||
<option value='polling'>轮询[默认]</option>\
|
||||
<option value='ip_hash'>ip_hash</option>\
|
||||
<option value='fair'>fair</option>\
|
||||
<option value='url_hash'>url_hash</option>\
|
||||
<option value='least_conn'>least_conn</option>\
|
||||
</select>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点健康检查</span>\
|
||||
<div class='info-r'>\
|
||||
<input type='checkbox' name='node_health_check'>\
|
||||
</div>\
|
||||
</div>\
|
||||
<div class='line'>\
|
||||
<span class='tname'>节点</span>\
|
||||
<div class='info-r'>\
|
||||
<div class='table-con divtable' style='max-height:120px;overflow:auto; margin-bottom:8px;width:95%'>\
|
||||
<table class='table table-hover' id='fixTable3'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>IP地址</th>\
|
||||
<th width='60'>端口</th>\
|
||||
<th width='120'>验证路径</th>\
|
||||
<th width='60'>状态</th>\
|
||||
<th width='60'>权重</th>\
|
||||
<th width='60'>阀值</th>\
|
||||
<th width='120'>恢复时间</th>\
|
||||
<th width='80' class='text-right'>操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id='nodecon'>\
|
||||
<tr class='nulltr'>\
|
||||
<td colspan='8' align='center'>当前节点为空,请至少添加一个普通节点</td>\
|
||||
</tr>\
|
||||
</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
<span class='btn btn-success btn-sm add_node' style='vertical-align:0'>添加节点</span>\
|
||||
</div>\
|
||||
</div>\
|
||||
</form>",
|
||||
success:function(){
|
||||
$('input[name="upstream_name"]').val(data['upstream_name']);
|
||||
$('select[name="node_algo"]').val(data['node_algo']);
|
||||
|
||||
$('input[name="node_health_check"]').prop('checked',false);
|
||||
if (data['node_health_check'] == 'ok'){
|
||||
$('input[name="node_health_check"]').prop('checked',true);
|
||||
}
|
||||
|
||||
var node_list = data['node_list'];
|
||||
if (node_list.length>0){
|
||||
$('#nodecon .nulltr').hide();
|
||||
}
|
||||
|
||||
var state_option_list = {
|
||||
'1':'参与者',
|
||||
'2':'备份',
|
||||
'0':'停用',
|
||||
}
|
||||
|
||||
for (var n in node_list) {
|
||||
|
||||
var tbody = '<tr>';
|
||||
tbody +='<td>'+node_list[n]['ip']+'</td>';
|
||||
tbody +='<td>'+node_list[n]['port']+'</td>';
|
||||
tbody +='<td>'+node_list[n]['path']+'</td>';
|
||||
|
||||
tbody +="<td><select name='state'>";
|
||||
|
||||
for (i in state_option_list) {
|
||||
if (i == node_list[n]['state']){
|
||||
tbody +="<option value='"+i+"' selected>"+state_option_list[i]+"</option>";
|
||||
} else{
|
||||
tbody +="<option value='"+i+"'>"+state_option_list[i]+"</option>";
|
||||
}
|
||||
}
|
||||
tbody +="</select></td>";
|
||||
|
||||
tbody +='<td><input type="number" name="weight" value="'+node_list[n]['weight']+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="max_fails" value="'+node_list[n]['max_fails']+'" style="width:50px"></td>';
|
||||
tbody +='<td><input type="number" name="fail_timeout" value="'+node_list[n]['fail_timeout']+'" style="width:50px"></td>';
|
||||
tbody +='<td class="text-right" width="50"><a class="btlink minus delete">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
$('#nodecon').append(tbody);
|
||||
}
|
||||
|
||||
$('#nodecon .delete').click(function(){
|
||||
$(this).parent().parent().remove();
|
||||
if ($('#nodecon tr').length == 1 ){
|
||||
$('#nodecon .nulltr').show();
|
||||
}
|
||||
});
|
||||
|
||||
$('.add_node').click(function(){
|
||||
addNode();
|
||||
});
|
||||
},
|
||||
yes:function(index) {
|
||||
var data = {};
|
||||
|
||||
data['node_algo'] = $('select[name="node_algo"]').val();
|
||||
data['node_health_check'] = 'fail';
|
||||
if ($('input[name="node_health_check"]').prop('checked')){
|
||||
data['node_health_check'] = 'ok';
|
||||
}
|
||||
|
||||
var node_list = [];
|
||||
$('#nodecon tr').each(function(){
|
||||
|
||||
var ip = $(this).find('td').eq(0).text();
|
||||
var port = $(this).find('td').eq(1).text();
|
||||
|
||||
if (port == ''){return;}
|
||||
|
||||
var path = $(this).find('td').eq(2).text();
|
||||
var state = $(this).find('select[name="state"]').val();
|
||||
var weight = $(this).find('input[name="weight"]').val();
|
||||
var max_fails = $(this).find('input[name="max_fails"]').val();
|
||||
var fail_timeout = $(this).find('input[name="fail_timeout"]').val();
|
||||
|
||||
var tmp = {
|
||||
ip:ip,
|
||||
port:port,
|
||||
path:path,
|
||||
state:state,
|
||||
weight:weight,
|
||||
max_fails:max_fails,
|
||||
fail_timeout:fail_timeout,
|
||||
}
|
||||
node_list.push(tmp);
|
||||
});
|
||||
data['node_list'] = node_list;
|
||||
data['row'] = row;
|
||||
ooPostCallbak('edit_load_balance', data, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
layer.close(index);
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function loadBalanceListRender(){
|
||||
ooPost('load_balance_list', {}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
var alist = rdata.data;
|
||||
|
||||
var tbody = '';
|
||||
for (var i = 0; i < alist.length; i++) {
|
||||
tbody += '<tr>';
|
||||
tbody += '<td>'+alist[i]['domain']+'</td>';
|
||||
tbody += '<td>'+alist[i]['upstream_name']+'</td>';
|
||||
tbody += '<td>'+alist[i]['node_list'].length+'</td>';
|
||||
tbody += '<td><a class="btlink log_look" data-row="'+i+'">查看</a></td>';
|
||||
tbody += '<td><a class="btlink health_status" data-row="'+i+'">查看</a></td>';
|
||||
tbody += '<td style="text-align: right;"><a class="btlink edit" data-row="'+i+'">修改</a> | <a class="btlink delete" data-row="'+i+'">删除</a></td>';
|
||||
tbody += '</tr>';
|
||||
}
|
||||
|
||||
$('#nodeTable').html(tbody);
|
||||
$('.nodeTablePage .Pcount').text('共'+alist.length+'条');
|
||||
$('#nodeTable .edit').click(function(){
|
||||
var row = $(this).data('row');
|
||||
editBalance(alist[row],row);
|
||||
});
|
||||
|
||||
$('#nodeTable .log_look').click(function(){
|
||||
var row = $(this).data('row');
|
||||
var args = {'domain':alist[row]['domain']};
|
||||
pluginRollingLogs('op_load_balance','','get_logs',JSON.stringify(args),20);
|
||||
});
|
||||
|
||||
$('#nodeTable .health_status').click(function(){
|
||||
var row = $(this).data('row');
|
||||
ooPost('get_health_status', {row:row}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
|
||||
var tval = '';
|
||||
for (var i = 0; i < rdata.data.length; i++) {
|
||||
tval += '<tr>';
|
||||
tval += '<td>'+rdata.data[i]['name']+'</td>';
|
||||
|
||||
if (typeof(rdata.data[i]['down']) != 'undefined' && rdata.data[i]['down']){
|
||||
tval += '<td><span style="color:red;">不正常</span></td>';
|
||||
} else{
|
||||
tval += '<td><span class="btlink">正常</span></td>';
|
||||
}
|
||||
tval += '</tr>';
|
||||
}
|
||||
|
||||
var tbody = "<div class='bt-form pd20'>\
|
||||
<div>\
|
||||
<div id='gitea_table' class='divtable' style='margin-top:5px;'>\
|
||||
<table class='table table-hover'>\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th width='120'>地址</th>\
|
||||
<th width='60'>状态</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody>"+tval+"</tbody>\
|
||||
</table>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>";
|
||||
|
||||
layer.open({
|
||||
type: 1,
|
||||
area: ['500px','300px'],
|
||||
title: '节点状态',
|
||||
closeBtn: 1,
|
||||
shift: 5,
|
||||
shadeClose: true,
|
||||
btn:['提交','关闭'],
|
||||
content:tbody,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
$('#nodeTable .delete').click(function(){
|
||||
var row = $(this).data('row');
|
||||
ooPost('load_balance_delete', {row:row}, function(rdata){
|
||||
var rdata = $.parseJSON(rdata.data);
|
||||
showMsg(rdata.msg, function(){
|
||||
loadBalanceListRender();
|
||||
},{ icon: rdata.status ? 1 : 2 }, 2000);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
function loadBalanceList() {
|
||||
var body = '<div class="bt-box active" style="display: block;">\
|
||||
<div class="mb10">\
|
||||
<button class="btn btn-success btn-sm" data-index="0" onclick="addBalance()">添加负载</button>\
|
||||
<div class="divtable mt10">\
|
||||
<table class="table table-hover">\
|
||||
<thead>\
|
||||
<tr>\
|
||||
<th>网站</th>\
|
||||
<th>负载名称</th>\
|
||||
<th>节点</th>\
|
||||
<th>日志</th>\
|
||||
<th>状态</th>\
|
||||
<th width="100" style="text-align: right;">操作</th>\
|
||||
</tr>\
|
||||
</thead>\
|
||||
<tbody id="nodeTable"></tbody>\
|
||||
</table>\
|
||||
<div class="nodeTablePage page" data-type="nodePage">\
|
||||
<div><span class="Pcount">共0条</span></div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>\
|
||||
</div>';
|
||||
$(".soft-man-con").html(body);
|
||||
loadBalanceListRender();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
local hc = require "resty.upstream.healthcheck"
|
||||
local ok, err = hc.spawn_checker {
|
||||
shm = "healthcheck",
|
||||
type = "http",
|
||||
upstream = "{$UPSTREAM_NAME}",
|
||||
http_req = "GET / HTTP/1.0\r\nHost: {$UPSTREAM_NAME}\r\n\r\n",
|
||||
interval = 2000,
|
||||
timeout = 6000,
|
||||
fall = 3,
|
||||
rise = 2,
|
||||
valid_statuses = {200, 302},
|
||||
concurrency = 20,
|
||||
}
|
||||
|
||||
if not ok then
|
||||
ngx.log(ngx.ERR, "=======> load balance health checker error: ", err)
|
||||
return
|
||||
end
|
||||
@@ -533,49 +533,51 @@ end
|
||||
function waf()
|
||||
min_route()
|
||||
-- C:D("min_route")
|
||||
-- white ip
|
||||
if waf_ip_white() then return true end
|
||||
-- C:D("waf_ip_white")
|
||||
|
||||
-- url white
|
||||
if waf_url_white() then return true end
|
||||
-- C:D("waf_url_white")
|
||||
|
||||
-- black ip
|
||||
if waf_ip_black() then return true end
|
||||
-- C:D("waf_ip_black")
|
||||
|
||||
-- 封禁ip返回
|
||||
if waf_drop_ip() then return true end
|
||||
-- C:D("waf_drop_ip")
|
||||
|
||||
-- ua check
|
||||
if waf_user_agent() then return true end
|
||||
-- C:D("waf_user_agent")
|
||||
if waf_url() then return true end
|
||||
-- C:D("waf_url")
|
||||
|
||||
-- cc setting
|
||||
if waf_cc_increase() then return true end
|
||||
-- C:D("waf_cc_increase")
|
||||
if waf_cc() then return true end
|
||||
-- C:D("waf_cc")
|
||||
|
||||
-- cookie检查
|
||||
if waf_cookie() then return true end
|
||||
-- C:D("waf_cookie")
|
||||
|
||||
-- args参数拦截
|
||||
if waf_get_args() then return true end
|
||||
-- C:D("waf_get_args")
|
||||
|
||||
-- 扫描软件禁止
|
||||
if waf_scan_black() then return true end
|
||||
-- C:D("waf_scan_black")
|
||||
if waf_post() then return true end
|
||||
-- C:D("waf_post")
|
||||
|
||||
if site_config[server_name] and site_config[server_name]['open'] then
|
||||
-- white ip
|
||||
if waf_ip_white() then return true end
|
||||
-- C:D("waf_ip_white")
|
||||
|
||||
-- url white
|
||||
if waf_url_white() then return true end
|
||||
-- C:D("waf_url_white")
|
||||
|
||||
-- black ip
|
||||
if waf_ip_black() then return true end
|
||||
-- C:D("waf_ip_black")
|
||||
|
||||
-- 封禁ip返回
|
||||
if waf_drop_ip() then return true end
|
||||
-- C:D("waf_drop_ip")
|
||||
|
||||
-- ua check
|
||||
if waf_user_agent() then return true end
|
||||
-- C:D("waf_user_agent")
|
||||
if waf_url() then return true end
|
||||
-- C:D("waf_url")
|
||||
|
||||
-- cc setting
|
||||
if waf_cc_increase() then return true end
|
||||
-- C:D("waf_cc_increase")
|
||||
if waf_cc() then return true end
|
||||
-- C:D("waf_cc")
|
||||
|
||||
-- cookie检查
|
||||
if waf_cookie() then return true end
|
||||
-- C:D("waf_cookie")
|
||||
|
||||
-- args参数拦截
|
||||
if waf_get_args() then return true end
|
||||
-- C:D("waf_get_args")
|
||||
|
||||
-- 扫描软件禁止
|
||||
if waf_scan_black() then return true end
|
||||
-- C:D("waf_scan_black")
|
||||
if waf_post() then return true end
|
||||
-- C:D("waf_post")
|
||||
--------------------------------------------------------
|
||||
--------------------------------------------------------
|
||||
if X_Forwarded() then return true end
|
||||
-- C:D("X_Forwarded")
|
||||
if post_X_Forwarded() then return true end
|
||||
|
||||
@@ -60,19 +60,26 @@ http
|
||||
limit_conn_zone $binary_remote_addr zone=perip:10m;
|
||||
limit_conn_zone $server_name zone=perserver:10m;
|
||||
|
||||
server_tokens off;
|
||||
access_log off;
|
||||
# CACEH_BEGIN
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 4k;
|
||||
proxy_buffers 512 4k;
|
||||
proxy_busy_buffers_size 64k;
|
||||
proxy_cache_path {$SERVER_PATH}/openresty/nginx/proxy_cache_temp levels=1:2 keys_zone=mw_cache:512m inactive=5m max_size=2g use_temp_path=off;
|
||||
#proxy timeout
|
||||
proxy_connect_timeout 3s;
|
||||
proxy_read_timeout 5s;
|
||||
proxy_send_timeout 5s;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name 127.0.0.1;
|
||||
allow 127.0.0.1;
|
||||
location /nginx_status {
|
||||
stub_status on;
|
||||
access_log off;
|
||||
}
|
||||
}
|
||||
fastcgi_cache_key "$scheme$request_method$host$request_uri";
|
||||
fastcgi_cache_path {$SERVER_PATH}/openresty/nginx/fastcgi_cache_temp levels=1:2 keys_zone=mw_cache_fcgi:100m inactive=60m max_size=5g;
|
||||
fastcgi_cache_use_stale error timeout invalid_header http_500;
|
||||
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
|
||||
# CACEH_END
|
||||
|
||||
server_tokens off;
|
||||
access_log /dev/null;
|
||||
|
||||
include {$SERVER_PATH}/web_conf/nginx/vhost/*.conf;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name 127.0.0.1;
|
||||
allow 127.0.0.1;
|
||||
location /nginx_status {
|
||||
stub_status on;
|
||||
access_log off;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
@@ -180,6 +180,17 @@ def confReplace():
|
||||
cmd_s = 'chmod u+s ' + ng_exe_bin
|
||||
os.system('echo %s|sudo -S %s' % (sudoPwd, cmd_s))
|
||||
|
||||
# vhost
|
||||
vhost_dir = mw.getServerDir() + '/web_conf/nginx/vhost'
|
||||
vhost_tpl_dir = getPluginDir() + '/conf/vhost'
|
||||
# print(vhost_dir, vhost_tpl_dir)
|
||||
vhost_list = ['0.websocket.conf', '0.nginx_status.conf']
|
||||
for f in vhost_list:
|
||||
a_conf = vhost_dir + '/' + f
|
||||
a_conf_tpl = vhost_tpl_dir + '/' + f
|
||||
if not os.path.exists(a_conf):
|
||||
mw.writeFile(a_conf, mw.readFile(a_conf_tpl))
|
||||
|
||||
|
||||
def initDreplace():
|
||||
|
||||
@@ -290,6 +301,7 @@ def restart():
|
||||
|
||||
|
||||
def reload():
|
||||
confReplace()
|
||||
return restyOp('reload')
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,6 @@
|
||||
"home":"http://openresty.org",
|
||||
"date":"2017-11-24",
|
||||
"pid": "1",
|
||||
"versions": ["1.17.8.2","1.19.3.1","1.21.4.1"],
|
||||
"updates": ["1.17.8.2","1.19.3.1","1.21.4.1"]
|
||||
"versions": ["1.17.8.2","1.19.3.1","1.21.4.2"],
|
||||
"updates": ["1.17.8.2","1.19.3.1","1.21.4.2"]
|
||||
}
|
||||
@@ -61,7 +61,18 @@ Install_openresty()
|
||||
|
||||
# wget -O openresty-1.21.4.1.tar.gz https://openresty.org/download/openresty-1.21.4.1.tar.gz
|
||||
if [ ! -f ${openrestyDir}/openresty-${VERSION}.tar.gz ];then
|
||||
wget -O ${openrestyDir}/openresty-${VERSION}.tar.gz https://openresty.org/download/openresty-${VERSION}.tar.gz
|
||||
wget --no-check-certificate -O ${openrestyDir}/openresty-${VERSION}.tar.gz https://openresty.org/download/openresty-${VERSION}.tar.gz -T 3
|
||||
fi
|
||||
|
||||
DOWNLOAD_SIZE=`wc -c ${openrestyDir}/openresty-${VERSION}.tar.gz | awk '{print $1}'`
|
||||
if [ "$DOWNLOAD_SIZE" == "0" ];then
|
||||
echo 'download failed, download again'
|
||||
rm -rf ${openrestyDir}/openresty-${VERSION}.tar.gz
|
||||
fi
|
||||
|
||||
# Last Download Method
|
||||
if [ ! -f ${openrestyDir}/openresty-${VERSION}.tar.gz ];then
|
||||
wget --no-check-certificate -O ${openrestyDir}/openresty-${VERSION}.tar.gz https://dl.midoks.me/soft/openresty/openresty-${VERSION}.tar.gz -T 3
|
||||
fi
|
||||
|
||||
cd ${openrestyDir} && tar -zxvf openresty-${VERSION}.tar.gz
|
||||
|
||||
@@ -658,7 +658,7 @@ function phpLibConfig(version){
|
||||
|
||||
//安装扩展
|
||||
function installPHPLib(version, name, title, pathinfo) {
|
||||
layer.confirm('您真的要安装{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
layer.confirm('您真的要卸载{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
name = name.toLowerCase();
|
||||
var data = "name=" + name + "&version=" + version + "&type=1";
|
||||
|
||||
|
||||
@@ -672,7 +672,7 @@ function installPHPLib(version, name, title, pathinfo) {
|
||||
|
||||
//卸载扩展
|
||||
function uninstallPHPLib(version, name, title, pathinfo) {
|
||||
layer.confirm('您真的要安装{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
layer.confirm('您真的要卸载{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
name = name.toLowerCase();
|
||||
var data = 'name=' + name + '&version=' + version;
|
||||
phpPost('uninstall_lib', version, data, function(data){
|
||||
|
||||
@@ -12,9 +12,9 @@ version=$1
|
||||
action=$2
|
||||
|
||||
if [ -f /lib/systemd/system/php${version}-php-fpm.service ];then
|
||||
systemctl ${action} php${version}
|
||||
systemctl ${action} php${version}-php-fpm
|
||||
elif [[ -f /usr/lib/systemd/system/php${version}-php-fpm.service ]]; then
|
||||
systemctl ${action} php${version}
|
||||
systemctl ${action} php${version}-php-fpm
|
||||
else
|
||||
$serverPath/php/init.d/php${version} ${action}
|
||||
fi
|
||||
@@ -7,6 +7,7 @@ Description=The PHP {$VERSION} FastCGI Process Manager
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Environment="LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/www/server/lib/icu/lib"
|
||||
PIDFile={$SERVER_PATH}/php/{$VERSION}/var/run/php-fpm.pid
|
||||
ExecStart={$SERVER_PATH}/php/{$VERSION}/sbin/php-fpm --nodaemonize --fpm-config {$SERVER_PATH}/php/{$VERSION}/etc/php-fpm.conf
|
||||
ExecReload=/bin/kill -USR2 $MAINPID
|
||||
|
||||
@@ -49,6 +49,7 @@ fi
|
||||
|
||||
cd ${curPath} && sh -x $curPath/versions/$2/install.sh $1
|
||||
|
||||
|
||||
if [ "${action}" == "install" ] && [ -d ${serverPath}/php/${type} ];then
|
||||
|
||||
#初始化
|
||||
@@ -59,6 +60,7 @@ if [ "${action}" == "install" ] && [ -d ${serverPath}/php/${type} ];then
|
||||
echo "install PHP${type} extend start"
|
||||
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash iconv.sh install 53
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash intl.sh install 73
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash gd.sh install 56
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash openssl.sh install 56
|
||||
# cd /www/server/mdserver-web/plugins/php/versions/common && bash sodium.sh install 81
|
||||
@@ -72,7 +74,6 @@ if [ "${action}" == "install" ] && [ -d ${serverPath}/php/${type} ];then
|
||||
cd ${rootPath}/plugins/php/versions/common && bash gettext.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash redis.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash memcached.sh install ${type}
|
||||
cd ${rootPath}/plugins/php/versions/common && bash zlib.sh install ${type}
|
||||
|
||||
if [ "${type}" -gt "72" ];then
|
||||
cd ${rootPath}/plugins/php/versions/common && bash zip.sh install ${type}
|
||||
|
||||
@@ -665,7 +665,7 @@ function installPHPLib(version, name, title, pathinfo) {
|
||||
|
||||
//卸载扩展
|
||||
function uninstallPHPLib(version, name, title, pathinfo) {
|
||||
layer.confirm('您真的要安装{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
layer.confirm('您真的要卸载{1}吗?'.replace('{1}', name), { icon: 3, closeBtn: 2 }, function() {
|
||||
name = name.toLowerCase();
|
||||
var data = 'name=' + name + '&version=' + version;
|
||||
phpPost('uninstall_lib', version, data, function(data){
|
||||
|
||||
@@ -15,11 +15,20 @@ SOURCE_ROOT=$rootPath/source/lib
|
||||
|
||||
if [ ! -d ${SERVER_ROOT}/freetype ];then
|
||||
cd $SOURCE_ROOT
|
||||
wget -O freetype-2.12.1.tar.gz --no-check-certificate https://download.savannah.gnu.org/releases/freetype/freetype-2.12.1.tar.gz -T 5
|
||||
tar zxvf freetype-2.12.1.tar.gz
|
||||
cd freetype-2.12.1
|
||||
|
||||
if [ ! -f $SOURCE_ROOT/freetype-2.12.1.tar.gz ];then
|
||||
wget -O freetype-2.12.1.tar.gz --no-check-certificate https://download.savannah.gnu.org/releases/freetype/freetype-2.12.1.tar.gz -T 5
|
||||
fi
|
||||
|
||||
if [ ! -d $SOURCE_ROOT/freetype-2.12.1 ];then
|
||||
tar zxvf freetype-2.12.1.tar.gz
|
||||
cd freetype-2.12.1
|
||||
else
|
||||
cd freetype-2.12.1
|
||||
fi
|
||||
|
||||
./configure --prefix=${SERVER_ROOT}/freetype && make && make install
|
||||
cd $SOURCE_ROOT
|
||||
cd $SOURCE_ROOT && rm -rf freetype-2.12.1
|
||||
#rm -rf freetype-2.12.1.tar.gz
|
||||
#rm -rf freetype-2.12.1
|
||||
|
||||
fi
|
||||
@@ -15,11 +15,20 @@ SOURCE_ROOT=$rootPath/source/lib
|
||||
|
||||
if [ ! -d ${SERVER_ROOT}/freetype_old ];then
|
||||
cd $SOURCE_ROOT
|
||||
wget -O freetype-2.7.1.tar.gz --no-check-certificate https://download.savannah.gnu.org/releases/freetype/freetype-2.7.1.tar.gz -T 5
|
||||
tar zxvf freetype-2.7.1.tar.gz
|
||||
cd freetype-2.7.1
|
||||
|
||||
if [ ! -f $SOURCE_ROOT/freetype-2.7.1.tar.gz ];then
|
||||
wget -O freetype-2.7.1.tar.gz --no-check-certificate https://download.savannah.gnu.org/releases/freetype/freetype-2.7.1.tar.gz -T 5
|
||||
fi
|
||||
|
||||
if [ ! -d $SOURCE_ROOT/freetype-2.7.1 ];then
|
||||
tar zxvf freetype-2.7.1.tar.gz
|
||||
cd freetype-2.7.1
|
||||
else
|
||||
cd freetype-2.7.1
|
||||
fi
|
||||
|
||||
./configure --prefix=${SERVER_ROOT}/freetype_old && make && make install
|
||||
#cd $SOURCE_ROOT
|
||||
cd $SOURCE_ROOT && rm -rf freetype-2.7.1
|
||||
|
||||
#rm -rf freetype-2.7.1.tar.gz
|
||||
#rm -rf freetype-2.7.1
|
||||
fi
|
||||
@@ -13,19 +13,29 @@ rootPath=$(dirname "$rootPath")
|
||||
SERVER_ROOT=$rootPath/lib
|
||||
SOURCE_ROOT=$rootPath/source/lib
|
||||
|
||||
|
||||
cn=$(curl -fsSL -m 10 http://ipinfo.io/json | grep "\"country\": \"CN\"")
|
||||
HTTP_PREFIX="https://"
|
||||
if [ ! -z "$cn" ];then
|
||||
HTTP_PREFIX="https://ghproxy.com/"
|
||||
fi
|
||||
|
||||
if [ ! -d ${SERVER_ROOT}/libzip ];then
|
||||
|
||||
cd $SOURCE_ROOT
|
||||
if [ ! -f ${SOURCE_ROOT}/libzip-1.3.2.tar.gz ];then
|
||||
wget --no-check-certificate -O libzip-1.3.2.tar.gz --no-check-certificate https://nih.at/libzip/libzip-1.3.2.tar.gz -T 20
|
||||
wget --no-check-certificate -O libzip-1.3.2.tar.gz ${HTTP_PREFIX}github.com/midoks/mdserver-web/releases/download/init/libzip-1.3.2.tar.gz -T 20
|
||||
fi
|
||||
|
||||
tar -zxvf libzip-1.3.2.tar.gz
|
||||
cd libzip-1.3.2
|
||||
cd ${SOURCE_ROOT}/libzip-1.3.2
|
||||
|
||||
./configure --prefix=${SERVER_ROOT}/libzip && make && make install
|
||||
|
||||
#cd $SOURCE_ROOT
|
||||
#rm -rf libzip-1.3.2
|
||||
#rm -rf libzip-1.3.2.tar.gz
|
||||
|
||||
if [ "$?" == "0" ];then
|
||||
rm -rf ${SOURCE_ROOT}/libzip-1.3.2
|
||||
rm -rf ${SOURCE_ROOT}/libzip-1.3.2.tar.gz
|
||||
fi
|
||||
|
||||
fi
|
||||
@@ -24,6 +24,22 @@ mkdir -p $serverPath/php
|
||||
cd ${rootPath}/plugins/php/lib && /bin/bash zlib.sh
|
||||
|
||||
if [ ! -d $sourcePath/php/php${PHP_VER} ];then
|
||||
|
||||
# ----------------------------------------------------------------------- #
|
||||
# 中国优化安装
|
||||
cn=$(curl -fsSL -m 10 -s http://ipinfo.io/json | grep "\"country\": \"CN\"")
|
||||
LOCAL_ADDR=common
|
||||
if [ ! -z "$cn" ];then
|
||||
LOCAL_ADDR=cn
|
||||
fi
|
||||
|
||||
if [ "$LOCAL_ADDR" == "cn" ];then
|
||||
if [ ! -f $sourcePath/php/php-${version}.tar.xz ];then
|
||||
wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.xz https://mirrors.sohu.com/php/php-${version}.tar.xz
|
||||
fi
|
||||
fi
|
||||
# ----------------------------------------------------------------------- #
|
||||
|
||||
if [ ! -f $sourcePath/php/php-${version}.tar.gz ];then
|
||||
wget --no-check-certificate -O $sourcePath/php/php-${version}.tar.gz https://museum.php.net/php5/php-${version}.tar.gz
|
||||
fi
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user