Compare commits
785 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6de9b5b09 | ||
|
|
f3ed064c10 | ||
|
|
00d8588abd | ||
|
|
a987837904 | ||
|
|
4bcad223ca | ||
|
|
b9e5005d05 | ||
|
|
fd9bdee6be | ||
|
|
4460956de6 | ||
|
|
1923c2706a | ||
|
|
1470ec2b65 | ||
|
|
62fc9bcc68 | ||
|
|
8a08df8593 | ||
|
|
bc7a1f37b6 | ||
|
|
f8a01e4639 | ||
|
|
8e4c00ef31 | ||
|
|
dc894828e0 | ||
|
|
7f6d8ba7b4 | ||
|
|
b8b56db83c | ||
|
|
17f0821945 | ||
|
|
b5436a6e57 | ||
|
|
46fe2d8369 | ||
|
|
ff429c270d | ||
|
|
92de19e359 | ||
|
|
4121c81a0a | ||
|
|
f639ab8342 | ||
|
|
f17a8ab1d0 | ||
|
|
12f677eb12 | ||
|
|
7595bdeb6b | ||
|
|
fc223af3f0 | ||
|
|
ebe3632f07 | ||
|
|
930babc010 | ||
|
|
255e3a61e6 | ||
|
|
52155a23ab | ||
|
|
200f244c0c | ||
|
|
ab5d7539ce | ||
|
|
3e79840fe6 | ||
|
|
d03455e3b0 | ||
|
|
af1cb14110 | ||
|
|
0feffa755e | ||
|
|
7cfbe2e473 | ||
|
|
7f63dc4565 | ||
|
|
e90424f80a | ||
|
|
6271125296 | ||
|
|
44ac4b83c5 | ||
|
|
c75e2c55c6 | ||
|
|
51a3029c09 | ||
|
|
580341d397 | ||
|
|
fb4bad0731 | ||
|
|
70efff2e6b | ||
|
|
97c76ef22f | ||
|
|
e763095756 | ||
|
|
b7dc2738e2 | ||
|
|
3db826b578 | ||
|
|
dc8975e374 | ||
|
|
c0cbd7c607 | ||
|
|
4d9f404bb0 | ||
|
|
06bb61804b | ||
|
|
32c1442878 | ||
|
|
b99652801d | ||
|
|
be565a98b9 | ||
|
|
5195a380db | ||
|
|
8dbbabb0e8 | ||
|
|
bec4500746 | ||
|
|
66a31f599d | ||
|
|
534cfb2180 | ||
|
|
a9dc20ffbd | ||
|
|
7f20ad32b6 | ||
|
|
a3c0b43bc4 | ||
|
|
1f2c9a6b3a | ||
|
|
194b0ec184 | ||
|
|
c94895a7c4 | ||
|
|
22d15bcb27 | ||
|
|
361fb9b868 | ||
|
|
2d675f4281 | ||
|
|
e19bbdf891 | ||
|
|
d48c0a2328 | ||
|
|
a70b20cf13 | ||
|
|
eb83017ed4 | ||
|
|
98ba31174b | ||
|
|
aa28e84507 | ||
|
|
da8fe918fe | ||
|
|
2b26bed97c | ||
|
|
5e50518bd9 | ||
|
|
e49db916f8 | ||
|
|
16083fd0d7 | ||
|
|
e0e2729fef | ||
|
|
9b95042936 | ||
|
|
44d45c53a1 | ||
|
|
c5fb340eb7 | ||
|
|
cbb61d2f0e | ||
|
|
a143714370 | ||
|
|
0e1a98c5d8 | ||
|
|
707a9f8caf | ||
|
|
da391f565b | ||
|
|
78f396129f | ||
|
|
e8b620aa1e | ||
|
|
1019370f37 | ||
|
|
cd7cff4f9c | ||
|
|
2888634fb0 | ||
|
|
94defc3e0c | ||
|
|
9089ed2657 | ||
|
|
b60bb5f6da | ||
|
|
ff4ea41963 | ||
|
|
b7dccad449 | ||
|
|
7fead214d4 | ||
|
|
d9590ec605 | ||
|
|
20b936580f | ||
|
|
b7b43bc31f | ||
|
|
6fd4f26755 | ||
|
|
f15d114708 | ||
|
|
fc24195b55 | ||
|
|
ed5de57244 | ||
|
|
4ce347738f | ||
|
|
f6e725781c | ||
|
|
55d70418cc | ||
|
|
7f5b070e36 | ||
|
|
993c7ee822 | ||
|
|
b5bb4e0df9 | ||
|
|
9f120fd0e0 | ||
|
|
77d614c9ea | ||
|
|
531ec3c55d | ||
|
|
0d6c064194 | ||
|
|
180e86c643 | ||
|
|
86b04b2b6b | ||
|
|
7a5ec79ace | ||
|
|
7290ffd2cd | ||
|
|
2f361c5bcc | ||
|
|
500d72aaf3 | ||
|
|
9fc391d1e8 | ||
|
|
c86e3e2047 | ||
|
|
7e72a90f53 | ||
|
|
7692fed38d | ||
|
|
bdd7d2a181 | ||
|
|
118c3f79e4 | ||
|
|
804a33a002 | ||
|
|
fe00588039 | ||
|
|
67aac200a7 | ||
|
|
3e01ad4b68 | ||
|
|
b39690484e | ||
|
|
31a69ecb12 | ||
|
|
94b95beadf | ||
|
|
6143f08cf2 | ||
|
|
73a5814fd6 | ||
|
|
448152d5c2 | ||
|
|
eedb3fb338 | ||
|
|
06f6f68f3a | ||
|
|
903e524e80 | ||
|
|
fa6b4fcaee | ||
|
|
67cc8e515f | ||
|
|
fa29817920 | ||
|
|
794c3bc132 | ||
|
|
9e481d31ac | ||
|
|
4ebc03af75 | ||
|
|
80e2face67 | ||
|
|
815a5187d5 | ||
|
|
1d7bc42fba | ||
|
|
1eb9cca793 | ||
|
|
8766f5b1a9 | ||
|
|
823e42626d | ||
|
|
c5308cf41c | ||
|
|
3053157c6e | ||
|
|
d1ba141c65 | ||
|
|
034ababead | ||
|
|
f5450e37be | ||
|
|
549fca93e6 | ||
|
|
efa0f33256 | ||
|
|
977a12843c | ||
|
|
6de2834a8c | ||
|
|
51f91e1603 | ||
|
|
d27b7c8fa1 | ||
|
|
c5098c66af | ||
|
|
c2635b0d04 | ||
|
|
41a1a6a2e5 | ||
|
|
e437117e69 | ||
|
|
fdc8f78229 | ||
|
|
2f78d76a1a | ||
|
|
742f2f0216 | ||
|
|
89a606329f | ||
|
|
3bba79d14c | ||
|
|
9f9787e30f | ||
|
|
529016d4d5 | ||
|
|
63942bfb08 | ||
|
|
f4e4f32f9c | ||
|
|
0a3c740502 | ||
|
|
9a3438e066 | ||
|
|
814b82e1b6 | ||
|
|
89cfd175cd | ||
|
|
860816719e | ||
|
|
caa936f0ac | ||
|
|
97836a89eb | ||
|
|
84483dce61 | ||
|
|
a4eb7a47f3 | ||
|
|
20c84d7fe5 | ||
|
|
9d5acd2b36 | ||
|
|
7508f6b92b | ||
|
|
379030fe71 | ||
|
|
10027eea20 | ||
|
|
69f25a176b | ||
|
|
ac19f06b6c | ||
|
|
87a81f59c7 | ||
|
|
7389e5e54b | ||
|
|
e6792b8188 | ||
|
|
a037546cfa | ||
|
|
8efaacf1ef | ||
|
|
a38dd1cef8 | ||
|
|
77521112d0 | ||
|
|
4f9a5d238c | ||
|
|
d5fb39ed50 | ||
|
|
58a84083ae | ||
|
|
9f564a4739 | ||
|
|
c20accbf58 | ||
|
|
3f21b3148e | ||
|
|
74e909a501 | ||
|
|
4150ee1b47 | ||
|
|
df04de2151 | ||
|
|
4dc5d9aa7e | ||
|
|
0ef7e6ccd8 | ||
|
|
ed2b831e5a | ||
|
|
5d392ecd43 | ||
|
|
ea147d7506 | ||
|
|
b45136c2c8 | ||
|
|
530e1513ec | ||
|
|
6c60677b72 | ||
|
|
a1bec5e578 | ||
|
|
9dece058d9 | ||
|
|
89df6ae6bf | ||
|
|
85b6e6428c | ||
|
|
0df204a1df | ||
|
|
ecef94b700 | ||
|
|
a493bbb280 | ||
|
|
eee902abec | ||
|
|
2aceb4fb4d | ||
|
|
c1bbcc8dab | ||
|
|
262f8a5594 | ||
|
|
a85b49a377 | ||
|
|
75e353db0e | ||
|
|
ccbb14836e | ||
|
|
7fbc61aa21 | ||
|
|
8b804cb500 | ||
|
|
3ddb95731a | ||
|
|
beeb46ab7f | ||
|
|
a65255e4e5 | ||
|
|
b7768ea0c0 | ||
|
|
9d2ecf6822 | ||
|
|
1a6d160a33 | ||
|
|
b69132e1ca | ||
|
|
19890c209f | ||
|
|
1534436435 | ||
|
|
c087d1cba2 | ||
|
|
cfc2ec5e4b | ||
|
|
af9c8523e9 | ||
|
|
00977cf33e | ||
|
|
fc2d018207 | ||
|
|
8569eebfee | ||
|
|
73d72f0d33 | ||
|
|
c4b8540171 | ||
|
|
85219ac2ef | ||
|
|
6976454bde | ||
|
|
813ce44ceb | ||
|
|
294b57ca60 | ||
|
|
22010190b2 | ||
|
|
cc4cd9c620 | ||
|
|
5df9c0f1fd | ||
|
|
dc3594a08d | ||
|
|
49ba1336cd | ||
|
|
96db5af237 | ||
|
|
476ff91bf8 | ||
|
|
ac6b10489e | ||
|
|
9352e1837f | ||
|
|
ddec102d18 | ||
|
|
0d50b9b0cc | ||
|
|
20b4b47eea | ||
|
|
ee8396c760 | ||
|
|
c3fa6a753a | ||
|
|
fbe4de2e94 | ||
|
|
f5c7108799 | ||
|
|
5825a7e654 | ||
|
|
a6911117af | ||
|
|
b428db4f5e | ||
|
|
e4145a2059 | ||
|
|
af13357985 | ||
|
|
1b949bd056 | ||
|
|
c4e415a72f | ||
|
|
39cb95184d | ||
|
|
a7abca6c09 | ||
|
|
894eff89ba | ||
|
|
35558f1d38 | ||
|
|
5a93ec0e32 | ||
|
|
73164de93e | ||
|
|
199349084e | ||
|
|
648fc2cac3 | ||
|
|
43f34950f3 | ||
|
|
1f0182e4a5 | ||
|
|
3f972571b0 | ||
|
|
0618ca9f8a | ||
|
|
efd0823b25 | ||
|
|
af5ca9faf5 | ||
|
|
87c5eeb829 | ||
|
|
df775272be | ||
|
|
dbeabe4379 | ||
|
|
dd33504416 | ||
|
|
d45dca4edb | ||
|
|
b4472271ce | ||
|
|
138eddf771 | ||
|
|
f0667abe55 | ||
|
|
873af38807 | ||
|
|
9bf46af088 | ||
|
|
3a3b5bca20 | ||
|
|
4806025f89 | ||
|
|
d7c757a2a1 | ||
|
|
3e8873d828 | ||
|
|
84484b6538 | ||
|
|
d36e9e80ee | ||
|
|
1fb831ca58 | ||
|
|
5e20553602 | ||
|
|
0f83d8ec66 | ||
|
|
e45a6cbcb5 | ||
|
|
ba1fd07555 | ||
|
|
a70b4bfaf3 | ||
|
|
9cf47ae1af | ||
|
|
7f58d65a57 | ||
|
|
4d40dd03de | ||
|
|
e3ce79c9fc | ||
|
|
f543edac1a | ||
|
|
1ce11a5745 | ||
|
|
ab56c7451a | ||
|
|
9800bbb661 | ||
|
|
8c4d2e7301 | ||
|
|
2c17675b6a | ||
|
|
3b30705f33 | ||
|
|
4cd9c5071d | ||
|
|
763a72d526 | ||
|
|
bd762ad10b | ||
|
|
56574ea3d9 | ||
|
|
6a31605519 | ||
|
|
c7abeeaf07 | ||
|
|
c11483ec6d | ||
|
|
c3713cefc9 | ||
|
|
2098bd4d32 | ||
|
|
7a6a02284e | ||
|
|
c749a7b088 | ||
|
|
1a91c7023e | ||
|
|
1da255d739 | ||
|
|
9103a979e4 | ||
|
|
768a2281e9 | ||
|
|
880d2e5861 | ||
|
|
adb10f8c1b | ||
|
|
f3afaefe7f | ||
|
|
64d514d02b | ||
|
|
9b6b40abfa | ||
|
|
6ccf64aa59 | ||
|
|
0e7c0d6441 | ||
|
|
36696c317d | ||
|
|
1cafbc8f72 | ||
|
|
e13abfc09e | ||
|
|
e89e11c421 | ||
|
|
c0ef64e935 | ||
|
|
5e7fe30984 | ||
|
|
bad1f34ac9 | ||
|
|
a1ac7b176b | ||
|
|
8dbfa96149 | ||
|
|
f47c9b9680 | ||
|
|
fcd1ffc893 | ||
|
|
c201f3e07c | ||
|
|
6512ecd1bc | ||
|
|
d26944893c | ||
|
|
23b77afc93 | ||
|
|
b512f3d680 | ||
|
|
d4e829e57c | ||
|
|
78798060e7 | ||
|
|
b2569a8dac | ||
|
|
4bd7ec9871 | ||
|
|
95cfad60c4 | ||
|
|
7f51d451f7 | ||
|
|
a4fb0fd795 | ||
|
|
c02928dd44 | ||
|
|
e70c49d407 | ||
|
|
e1c1984fd4 | ||
|
|
f801d304c6 | ||
|
|
178a38c6d9 | ||
|
|
e356707db7 | ||
|
|
8d3043d0fe | ||
|
|
1e494bd1fd | ||
|
|
b726c8d589 | ||
|
|
e71e80703d | ||
|
|
c9b666e5bc | ||
|
|
874139ea07 | ||
|
|
05d79ad606 | ||
|
|
13c78a5fec | ||
|
|
f3e3824b7d | ||
|
|
67473c2dcf | ||
|
|
3921c547be | ||
|
|
3e0d2fda6a | ||
|
|
7ff6c0c18b | ||
|
|
e76464673a | ||
|
|
1ab849d9b0 | ||
|
|
781c851571 | ||
|
|
0b19d93a47 | ||
|
|
2856f7716b | ||
|
|
c9ba24dc96 | ||
|
|
a660fb1f42 | ||
|
|
8586ad6478 | ||
|
|
0fab6fecfe | ||
|
|
d752bb08c7 | ||
|
|
6f845f36c9 | ||
|
|
66bc60a47c | ||
|
|
1c048da1f0 | ||
|
|
da8aa20f83 | ||
|
|
14315923d8 | ||
|
|
3d3228fe96 | ||
|
|
173ac5a8aa | ||
|
|
e9c5d7e7cf | ||
|
|
194127dce9 | ||
|
|
86cb7e9d41 | ||
|
|
b2774de6a2 | ||
|
|
3a4722b701 | ||
|
|
028aea4e3d | ||
|
|
c3dd97a7c1 | ||
|
|
d527fcdd78 | ||
|
|
d6f311e057 | ||
|
|
991e08fa71 | ||
|
|
06b44dc101 | ||
|
|
2d94b994fa | ||
|
|
c036186dde | ||
|
|
bc2ad13037 | ||
|
|
bfa04856aa | ||
|
|
feb1068441 | ||
|
|
181a4d05b0 | ||
|
|
c449265e05 | ||
|
|
e778616b5c | ||
|
|
dad5be2670 | ||
|
|
414afd17b8 | ||
|
|
86a806bca2 | ||
|
|
faed7420a7 | ||
|
|
ae14ff4f9f | ||
|
|
99e1658fdf | ||
|
|
e79264eefc | ||
|
|
dd0e26e7bc | ||
|
|
342c4bfbc2 | ||
|
|
7d2b8fd4c8 | ||
|
|
6426622992 | ||
|
|
3d154411de | ||
|
|
241f41e900 | ||
|
|
6c3d24d895 | ||
|
|
b2a0204f6b | ||
|
|
a9d71652b7 | ||
|
|
1b6bfb33d6 | ||
|
|
aec0d8d681 | ||
|
|
e38871b52d | ||
|
|
c1b4551dd1 | ||
|
|
d479140f87 | ||
|
|
881bb89ac0 | ||
|
|
0e4158f600 | ||
|
|
57bbd77ae5 | ||
|
|
6906b3094b | ||
|
|
aec28b5087 | ||
|
|
b59ed1f73e | ||
|
|
2a83f61bdd | ||
|
|
4f21d60ca4 | ||
|
|
0a6111b2e5 | ||
|
|
4b425e1698 | ||
|
|
bee7da807b | ||
|
|
a906a7db06 | ||
|
|
ea62cf0ff7 | ||
|
|
72e0c55f5d | ||
|
|
3a88f23181 | ||
|
|
967c9080fb | ||
|
|
f44b9434ad | ||
|
|
e21a3c5f8c | ||
|
|
88dae56b6c | ||
|
|
40c3475306 | ||
|
|
318c8dd566 | ||
|
|
a5f30b1573 | ||
|
|
a8ec959c70 | ||
|
|
c393b2f480 | ||
|
|
548f56f8f0 | ||
|
|
9aa71365b9 | ||
|
|
292fb72a26 | ||
|
|
e5315c3b8d | ||
|
|
a4dd7bb75a | ||
|
|
53ef0f3fb2 | ||
|
|
6af8bff802 | ||
|
|
d849f7440a | ||
|
|
425c0ec44c | ||
|
|
aad0b01581 | ||
|
|
bc2c3dfa0b | ||
|
|
0fe76430c6 | ||
|
|
979ff4c44e | ||
|
|
b0b6b5984f | ||
|
|
5d4da6cccb | ||
|
|
912ffa062f | ||
|
|
1db4661c75 | ||
|
|
f7dd9e3f39 | ||
|
|
0cc74b920e | ||
|
|
51c3807d01 | ||
|
|
c2c42ca2b7 | ||
|
|
2a6db6ebfe | ||
|
|
30d8edbdcf | ||
|
|
177afafe12 | ||
|
|
98765b6e2a | ||
|
|
e4e0aab010 | ||
|
|
ed87b4e2a9 | ||
|
|
337eb36d25 | ||
|
|
c44e40d72d | ||
|
|
2e8ba831a1 | ||
|
|
a706c2a5a5 | ||
|
|
093826222a | ||
|
|
0d7b487afc | ||
|
|
8de17b6d9c | ||
|
|
49d217a883 | ||
|
|
4827555899 | ||
|
|
41f3825ee2 | ||
|
|
096aa153ab | ||
|
|
8f8b611ac1 | ||
|
|
08b1c038f1 | ||
|
|
934b10a254 | ||
|
|
4947f13416 | ||
|
|
84198d5948 | ||
|
|
d4a04bc798 | ||
|
|
c94b3c26c1 | ||
|
|
5655f89ba6 | ||
|
|
c568ad3e9a | ||
|
|
d2f532447d | ||
|
|
ec97feab28 | ||
|
|
316cd36f71 | ||
|
|
702a0f1ecf | ||
|
|
2d2b7b7bff | ||
|
|
6f8c5a8e99 | ||
|
|
afb35953e7 | ||
|
|
2a1f78a440 | ||
|
|
fb084a9f48 | ||
|
|
e7f620d28f | ||
|
|
2f64d713e8 | ||
|
|
86bf316468 | ||
|
|
bf320271d4 | ||
|
|
150a63fe98 | ||
|
|
1d1ff11eb7 | ||
|
|
55eecce416 | ||
|
|
5f822062da | ||
|
|
ee2c253e7d | ||
|
|
5b0adb4b84 | ||
|
|
8c72540a6e | ||
|
|
7f811997a9 | ||
|
|
ca94e31451 | ||
|
|
320d381bd9 | ||
|
|
c8057457cc | ||
|
|
c78c4d58ff | ||
|
|
d1f8e7e757 | ||
|
|
5386b30eba | ||
|
|
8ceb1334cd | ||
|
|
023e563de1 | ||
|
|
39e6d11d71 | ||
|
|
a5a9117ce0 | ||
|
|
e95b0bd9a6 | ||
|
|
9699a9adad | ||
|
|
67729abd13 | ||
|
|
4c7ebce97a | ||
|
|
44e7ce9f79 | ||
|
|
3468fcf8a6 | ||
|
|
3522c22a28 | ||
|
|
333a9c6611 | ||
|
|
e3426a84e2 | ||
|
|
a25b0e6c9d | ||
|
|
c271cadabd | ||
|
|
428bb7eb0f | ||
|
|
6ae9f447b6 | ||
|
|
7cc503b698 | ||
|
|
c66e28cb9d | ||
|
|
e5109b24d4 | ||
|
|
695b8482de | ||
|
|
d0b908bcaa | ||
|
|
3de25d4fe1 | ||
|
|
07194855bf | ||
|
|
d0f1eb13ee | ||
|
|
a0930bfd74 | ||
|
|
08cff8affc | ||
|
|
02132e9262 | ||
|
|
61b6a49885 | ||
|
|
896e54ebe8 | ||
|
|
1b36bad60a | ||
|
|
fc14800d70 | ||
|
|
fa61f277e4 | ||
|
|
9117309472 | ||
|
|
6bb2977d59 | ||
|
|
df9dce76cb | ||
|
|
4cb9c85a1c | ||
|
|
f4f5389ffb | ||
|
|
5d336eb77d | ||
|
|
c552eb3b0e | ||
|
|
455952e9e4 | ||
|
|
7132401c7f | ||
|
|
a4dddfb139 | ||
|
|
7ef32bad97 | ||
|
|
732513a644 | ||
|
|
756cf4a9ae | ||
|
|
a15a630265 | ||
|
|
3fab1b8294 | ||
|
|
215635f429 | ||
|
|
dbb1ae180b | ||
|
|
e8d4d01d85 | ||
|
|
6593989a84 | ||
|
|
004e640321 | ||
|
|
7ad315ae4b | ||
|
|
ba938e5361 | ||
|
|
9ddf02a0e6 | ||
|
|
ebcbd5690d | ||
|
|
bbca766fa4 | ||
|
|
99c7819d3a | ||
|
|
08bb3e66f8 | ||
|
|
9159820742 | ||
|
|
1a565b2ebb | ||
|
|
98847c53ea | ||
|
|
14bafc8f20 | ||
|
|
58a5bd0092 | ||
|
|
4f1ce52f6a | ||
|
|
14ba7f6899 | ||
|
|
e582e37c06 | ||
|
|
6a3fa9f0ca | ||
|
|
e0a9965fed | ||
|
|
481fa8cd2d | ||
|
|
95349dc457 | ||
|
|
fc839f96d2 | ||
|
|
0414cc02e8 | ||
|
|
b8babaae39 | ||
|
|
285ce1b312 | ||
|
|
c309da81ae | ||
|
|
c325fde52b | ||
|
|
0f69b45d25 | ||
|
|
e02084ba5d | ||
|
|
642b23dbb7 | ||
|
|
b1dc385c87 | ||
|
|
89a69e3165 | ||
|
|
530954dd6c | ||
|
|
33635f7a1b | ||
|
|
8ac964e805 | ||
|
|
a1519baf0f | ||
|
|
e6e32a39bb | ||
|
|
d828b7f8a4 | ||
|
|
07b377c2fb | ||
|
|
33a3795773 | ||
|
|
bddb3cae96 | ||
|
|
6a525c2b82 | ||
|
|
3a137c1c3f | ||
|
|
19867568a9 | ||
|
|
c2600b911b | ||
|
|
fe511ae7e5 | ||
|
|
876c631c85 | ||
|
|
a4cc138ef3 | ||
|
|
3f9a7a8a49 | ||
|
|
09d8ef00c2 | ||
|
|
b4f77ddc63 | ||
|
|
6a9045ba44 | ||
|
|
bc7ee19962 | ||
|
|
2484cd4ae6 | ||
|
|
57b8a96c6d | ||
|
|
6c8ab7cb94 | ||
|
|
b2c2bd247b | ||
|
|
29d9e6db81 | ||
|
|
24fcb48c75 | ||
|
|
4911198fe7 | ||
|
|
c2af796992 | ||
|
|
51c8572e53 | ||
|
|
c15cc6d75c | ||
|
|
c0a99a4ba3 | ||
|
|
62e26bed5a | ||
|
|
9e68a2915c | ||
|
|
5b809fda1f | ||
|
|
88b782940a | ||
|
|
85c596644d | ||
|
|
ffa2d884bd | ||
|
|
813ed18610 | ||
|
|
564b11eae7 | ||
|
|
d2af0307b9 | ||
|
|
4fa6b03238 | ||
|
|
4bda78aa8c | ||
|
|
6002cc96d9 | ||
|
|
56c09f5be7 | ||
|
|
e1fb8e4c74 | ||
|
|
14f055ce7c | ||
|
|
7b7f2b0a00 | ||
|
|
75662586fa | ||
|
|
c024331fa0 | ||
|
|
b01ea79c5c | ||
|
|
d59f80b3ec | ||
|
|
b87e48c1f9 | ||
|
|
0e7a7f168f | ||
|
|
2bbc09d3af | ||
|
|
97b50fab28 | ||
|
|
83c867cb65 | ||
|
|
3c4b7ca57b | ||
|
|
a2f98d2f25 | ||
|
|
71677a8638 | ||
|
|
95a2187f95 | ||
|
|
86bec813bf | ||
|
|
0d7bd6f04e | ||
|
|
d7117209b2 | ||
|
|
7a340ac68b | ||
|
|
353b1b4ad1 | ||
|
|
fdac8beb40 | ||
|
|
f098723a41 | ||
|
|
6ded627903 | ||
|
|
ed2d5ee5cc | ||
|
|
c677368482 | ||
|
|
51ccd614a7 | ||
|
|
9be7f61b8c | ||
|
|
14ad97c937 | ||
|
|
94609d8ef4 | ||
|
|
e34e38bcb2 | ||
|
|
b10d9fe842 | ||
|
|
992e725378 | ||
|
|
346de7ca7a | ||
|
|
b212e124c2 | ||
|
|
ee2781fe65 | ||
|
|
89c1edc9ee | ||
|
|
773f3e1a7e | ||
|
|
e6f6f4dcc2 | ||
|
|
174946aa4d | ||
|
|
93c594a785 | ||
|
|
2aea527dff | ||
|
|
fa30015ca5 | ||
|
|
d06c8cebf5 | ||
|
|
e4ef2e8253 | ||
|
|
665aa06cc7 | ||
|
|
88dfda82d6 | ||
|
|
243463df83 | ||
|
|
2dc1bfcb55 | ||
|
|
e6f7cafe7e | ||
|
|
26fe3558f4 | ||
|
|
ea09ef3d91 | ||
|
|
c4ca2521ee | ||
|
|
db5cdd2957 | ||
|
|
0f483b98ec | ||
|
|
0fe51abeb1 | ||
|
|
db6b7f57bb | ||
|
|
663ead19e4 | ||
|
|
bc8adb663a | ||
|
|
08b5dd7531 | ||
|
|
8177f3d7e4 | ||
|
|
bb5252caf6 | ||
|
|
bd4a47d2a1 | ||
|
|
300be4e936 | ||
|
|
c9dbfb79a7 | ||
|
|
589ae124f1 | ||
|
|
d72b440406 | ||
|
|
63e4e7cf9f | ||
|
|
ad416dddec | ||
|
|
4e18129c6c | ||
|
|
c03d9f1880 | ||
|
|
fe448e6556 | ||
|
|
adcb33fce4 | ||
|
|
e58c3774b6 | ||
|
|
cd7e01c2f0 | ||
|
|
d884777a55 | ||
|
|
c48aba1c99 | ||
|
|
8cc0faf1d7 | ||
|
|
9851b1a146 | ||
|
|
36162c603d | ||
|
|
cc2782584e | ||
|
|
1c1e82ee38 | ||
|
|
4b3a9cedfa | ||
|
|
e9497ee65d | ||
|
|
29fae55dc6 | ||
|
|
54fdf3b762 | ||
|
|
f609008984 | ||
|
|
f9b6838dc6 | ||
|
|
6d2ecb9af3 | ||
|
|
7c4a01137b | ||
|
|
418c15f79f | ||
|
|
d13176b8a5 | ||
|
|
b2752ddd5a | ||
|
|
7aea2fd48c | ||
|
|
803f11659c | ||
|
|
073926ff67 | ||
|
|
65b4832c94 | ||
|
|
5f793f1f76 | ||
|
|
0ce1df25bc | ||
|
|
06ad9cc63b | ||
|
|
57247d0f5b | ||
|
|
813267c50f | ||
|
|
b8078e73b2 | ||
|
|
f958c57984 | ||
|
|
30bfbdc01e | ||
|
|
314362c24d | ||
|
|
8582715be7 | ||
|
|
74e585263c |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,2 +1,3 @@
|
||||
*_plus.go
|
||||
*-plus.sh
|
||||
*-plus.sh
|
||||
*_plus_test.go
|
||||
75
.golangci.yaml
Normal file
75
.golangci.yaml
Normal file
@@ -0,0 +1,75 @@
|
||||
# https://golangci-lint.run/usage/configuration/
|
||||
|
||||
linters:
|
||||
enable-all: true
|
||||
disable:
|
||||
- ifshort
|
||||
- exhaustivestruct
|
||||
- golint
|
||||
- nosnakecase
|
||||
- scopelint
|
||||
- varcheck
|
||||
- structcheck
|
||||
- interfacer
|
||||
- maligned
|
||||
- deadcode
|
||||
- dogsled
|
||||
- wrapcheck
|
||||
- wastedassign
|
||||
- varnamelen
|
||||
- testpackage
|
||||
- thelper
|
||||
- nilerr
|
||||
- sqlclosecheck
|
||||
- paralleltest
|
||||
- nonamedreturns
|
||||
- nlreturn
|
||||
- nakedret
|
||||
- ireturn
|
||||
- interfacebloat
|
||||
- gosmopolitan
|
||||
- gomnd
|
||||
- goerr113
|
||||
- gochecknoglobals
|
||||
- exhaustruct
|
||||
- errorlint
|
||||
- depguard
|
||||
- exhaustive
|
||||
- containedctx
|
||||
- wsl
|
||||
- cyclop
|
||||
- dupword
|
||||
- errchkjson
|
||||
- contextcheck
|
||||
- tagalign
|
||||
- dupl
|
||||
- forbidigo
|
||||
- funlen
|
||||
- goconst
|
||||
- godox
|
||||
- gosec
|
||||
- lll
|
||||
- nestif
|
||||
- revive
|
||||
- unparam
|
||||
- stylecheck
|
||||
- gocritic
|
||||
- gofumpt
|
||||
- gomoddirectives
|
||||
- godot
|
||||
- gofmt
|
||||
- gocognit
|
||||
- mirror
|
||||
- gocyclo
|
||||
- gochecknoinits
|
||||
- gci
|
||||
- maintidx
|
||||
- prealloc
|
||||
- goimports
|
||||
- errname
|
||||
- musttag
|
||||
- forcetypeassert
|
||||
- whitespace
|
||||
- noctx
|
||||
- tagliatelle
|
||||
- nilnil
|
||||
29
LICENSE
Normal file
29
LICENSE
Normal file
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2020, LiuXiangChao
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
104
build/build.sh
104
build/build.sh
@@ -1,76 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function build() {
|
||||
ROOT=$(dirname $0)
|
||||
ROOT=$(dirname "$0")
|
||||
NAME="edge-api"
|
||||
DIST=$ROOT/"../dist/${NAME}"
|
||||
OS=${1}
|
||||
ARCH=${2}
|
||||
TAG=${3}
|
||||
NODE_ARCHITECTS=("amd64" "386" "arm64" "mips64" "mips64le")
|
||||
NODE_ARCHITECTS=("amd64" "arm64")
|
||||
|
||||
if [ -z $OS ]; then
|
||||
if [ -z "$OS" ]; then
|
||||
echo "usage: build.sh OS ARCH"
|
||||
exit
|
||||
fi
|
||||
if [ -z $ARCH ]; then
|
||||
if [ -z "$ARCH" ]; then
|
||||
echo "usage: build.sh OS ARCH"
|
||||
exit
|
||||
fi
|
||||
if [ -z $TAG ]; then
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG="community"
|
||||
fi
|
||||
|
||||
VERSION=$(lookup-version $ROOT/../internal/const/const.go)
|
||||
VERSION=$(lookup-version "$ROOT"/../internal/const/const.go)
|
||||
ZIP="${NAME}-${OS}-${ARCH}-${TAG}-v${VERSION}.zip"
|
||||
|
||||
# build edge-node
|
||||
NodeVersion=$(lookup-version $ROOT"/../../EdgeNode/internal/const/const.go")
|
||||
NodeVersion=$(lookup-version "$ROOT""/../../EdgeNode/internal/const/const.go")
|
||||
echo "building edge-node v${NodeVersion} ..."
|
||||
EDGE_NODE_BUILD_SCRIPT=$ROOT"/../../EdgeNode/build/build.sh"
|
||||
if [ ! -f $EDGE_NODE_BUILD_SCRIPT ]; then
|
||||
if [ ! -f "$EDGE_NODE_BUILD_SCRIPT" ]; then
|
||||
echo "unable to find edge-node build script 'EdgeNode/build/build.sh'"
|
||||
exit
|
||||
fi
|
||||
cd $ROOT"/../../EdgeNode/build"
|
||||
cd "$ROOT""/../../EdgeNode/build" || exit
|
||||
echo "=============================="
|
||||
for arch in "${NODE_ARCHITECTS[@]}"; do
|
||||
if [ ! -f $ROOT"/../../EdgeNode/dist/edge-node-linux-${arch}-${TAG}-v${NodeVersion}.zip" ]; then
|
||||
./build.sh linux $arch $TAG
|
||||
if [ ! -f "$ROOT""/../../EdgeNode/dist/edge-node-linux-${arch}-${TAG}-v${NodeVersion}.zip" ]; then
|
||||
./build.sh linux "$arch" $TAG
|
||||
else
|
||||
echo "use built node linux/$arch/v${NodeVersion}"
|
||||
fi
|
||||
done
|
||||
echo "=============================="
|
||||
cd -
|
||||
cd - || exit
|
||||
|
||||
rm -f $ROOT/deploy/*.zip
|
||||
rm -f "$ROOT"/deploy/*.zip
|
||||
for arch in "${NODE_ARCHITECTS[@]}"; do
|
||||
cp $ROOT"/../../EdgeNode/dist/edge-node-linux-${arch}-${TAG}-v${NodeVersion}.zip" $ROOT/deploy/edge-node-linux-${arch}-v${NodeVersion}.zip
|
||||
cp "$ROOT""/../../EdgeNode/dist/edge-node-linux-${arch}-${TAG}-v${NodeVersion}.zip" "$ROOT"/deploy/edge-node-linux-"${arch}"-v"${NodeVersion}".zip
|
||||
done
|
||||
|
||||
# build edge-dns
|
||||
if [ "$TAG" = "plus" ]; then
|
||||
DNS_ROOT=$ROOT"/../../EdgeDNS"
|
||||
if [ -d $DNS_ROOT ]; then
|
||||
DNSNodeVersion=$(lookup-version $ROOT"/../../EdgeDNS/internal/const/const.go")
|
||||
if [ -d "$DNS_ROOT" ]; then
|
||||
DNSNodeVersion=$(lookup-version "$ROOT""/../../EdgeDNS/internal/const/const.go")
|
||||
echo "building edge-dns ${DNSNodeVersion} ..."
|
||||
EDGE_DNS_NODE_BUILD_SCRIPT=$ROOT"/../../EdgeDNS/build/build.sh"
|
||||
if [ ! -f $EDGE_DNS_NODE_BUILD_SCRIPT ]; then
|
||||
if [ ! -f "$EDGE_DNS_NODE_BUILD_SCRIPT" ]; then
|
||||
echo "unable to find edge-dns build script 'EdgeDNS/build/build.sh'"
|
||||
exit
|
||||
fi
|
||||
cd $ROOT"/../../EdgeDNS/build"
|
||||
cd "$ROOT""/../../EdgeDNS/build" || exit
|
||||
echo "=============================="
|
||||
architects=("amd64")
|
||||
architects=("amd64" "arm64")
|
||||
for arch in "${architects[@]}"; do
|
||||
./build.sh linux $arch $TAG
|
||||
./build.sh linux "$arch" $TAG
|
||||
done
|
||||
echo "=============================="
|
||||
cd -
|
||||
cd - || exit
|
||||
|
||||
for arch in "${architects[@]}"; do
|
||||
cp $ROOT"/../../EdgeDNS/dist/edge-dns-linux-${arch}-v${DNSNodeVersion}.zip" $ROOT/deploy/edge-dns-linux-${arch}-v${DNSNodeVersion}.zip
|
||||
cp "$ROOT""/../../EdgeDNS/dist/edge-dns-linux-${arch}-v${DNSNodeVersion}.zip" "$ROOT"/deploy/edge-dns-linux-"${arch}"-v"${DNSNodeVersion}".zip
|
||||
done
|
||||
fi
|
||||
fi
|
||||
@@ -78,48 +78,52 @@ function build() {
|
||||
# build sql
|
||||
if [ $TAG = "plus" ]; then
|
||||
echo "building sql ..."
|
||||
${ROOT}/sql.sh
|
||||
"${ROOT}"/sql.sh
|
||||
fi
|
||||
|
||||
# copy files
|
||||
echo "copying ..."
|
||||
if [ ! -d $DIST ]; then
|
||||
mkdir $DIST
|
||||
mkdir $DIST/bin
|
||||
mkdir $DIST/configs
|
||||
mkdir $DIST/logs
|
||||
if [ ! -d "$DIST" ]; then
|
||||
mkdir "$DIST"
|
||||
mkdir "$DIST"/bin
|
||||
mkdir "$DIST"/configs
|
||||
mkdir "$DIST"/logs
|
||||
mkdir "$DIST"/data
|
||||
fi
|
||||
cp $ROOT/configs/api.template.yaml $DIST/configs/
|
||||
cp $ROOT/configs/db.template.yaml $DIST/configs/
|
||||
cp -R $ROOT/deploy $DIST/
|
||||
rm -f $dist/deploy/.gitignore
|
||||
cp -R $ROOT/installers $DIST/
|
||||
cp -R $ROOT/resources $DIST/
|
||||
rm -f $DIST/resources/ipdata/ip2region/global_region.csv
|
||||
rm -f $DIST/resources/ipdata/ip2region/ip.merge.txt
|
||||
cp "$ROOT"/configs/api.template.yaml "$DIST"/configs/
|
||||
cp "$ROOT"/configs/db.template.yaml "$DIST"/configs/
|
||||
cp -R "$ROOT"/deploy "$DIST/"
|
||||
rm -f "$DIST"/deploy/.gitignore
|
||||
cp -R "$ROOT"/installers "$DIST"/
|
||||
|
||||
# building edge installer
|
||||
echo "building node installer ..."
|
||||
architects=("amd64" "386" "arm64")
|
||||
architects=("amd64" "arm64")
|
||||
for arch in "${architects[@]}"; do
|
||||
# TODO support arm, mips ...
|
||||
env GOOS=linux GOARCH=${arch} go build -tags $TAG --ldflags="-s -w" -o $ROOT/installers/edge-installer-helper-linux-${arch} $ROOT/../cmd/installer-helper/main.go
|
||||
env GOOS=linux GOARCH="${arch}" go build -trimpath -tags $TAG --ldflags="-s -w" -o "$ROOT"/installers/edge-installer-helper-linux-"${arch}" "$ROOT"/../cmd/installer-helper/main.go
|
||||
done
|
||||
|
||||
# building edge dns installer
|
||||
echo "building dns node installer ..."
|
||||
architects=("amd64" "386" "arm64")
|
||||
for arch in "${architects[@]}"; do
|
||||
# TODO support arm, mips ...
|
||||
env GOOS=linux GOARCH=${arch} go build -tags $TAG --ldflags="-s -w" -o $ROOT/installers/edge-installer-dns-helper-linux-${arch} $ROOT/../cmd/installer-dns-helper/main.go
|
||||
done
|
||||
if [ $TAG = "plus" ]; then
|
||||
echo "building dns node installer ..."
|
||||
architects=("amd64" "arm64")
|
||||
for arch in "${architects[@]}"; do
|
||||
# TODO support arm, mips ...
|
||||
env GOOS=linux GOARCH="${arch}" go build -trimpath -tags $TAG --ldflags="-s -w" -o "$ROOT"/installers/edge-installer-dns-helper-linux-"${arch}" "$ROOT"/../cmd/installer-dns-helper/main.go
|
||||
done
|
||||
fi
|
||||
|
||||
# building api node
|
||||
env GOOS=$OS GOARCH=$ARCH go build -tags $TAG --ldflags="-s -w" -o $DIST/bin/edge-api $ROOT/../cmd/edge-api/main.go
|
||||
env GOOS="$OS" GOARCH="$ARCH" go build -trimpath -tags $TAG --ldflags="-s -w" -o "$DIST/bin/$NAME" "$ROOT"/../cmd/edge-api/main.go
|
||||
if [ ! -f "${DIST}/bin/${NAME}" ]; then
|
||||
echo "build failed!"
|
||||
exit
|
||||
fi
|
||||
|
||||
# delete hidden files
|
||||
find $DIST -name ".DS_Store" -delete
|
||||
find $DIST -name ".gitignore" -delete
|
||||
find "$DIST" -name ".DS_Store" -delete
|
||||
find "$DIST" -name ".gitignore" -delete
|
||||
|
||||
echo "zip files"
|
||||
cd "${DIST}/../" || exit
|
||||
@@ -135,15 +139,15 @@ function build() {
|
||||
|
||||
function lookup-version() {
|
||||
FILE=$1
|
||||
VERSION_DATA=$(cat $FILE)
|
||||
VERSION_DATA=$(cat "$FILE")
|
||||
re="Version[ ]+=[ ]+\"([0-9.]+)\""
|
||||
if [[ $VERSION_DATA =~ $re ]]; then
|
||||
VERSION=${BASH_REMATCH[1]}
|
||||
echo $VERSION
|
||||
echo "$VERSION"
|
||||
else
|
||||
echo "could not match version"
|
||||
exit
|
||||
fi
|
||||
}
|
||||
|
||||
build $1 $2 $3
|
||||
build "$1" "$2" "$3"
|
||||
|
||||
@@ -9,3 +9,8 @@ dbs:
|
||||
prefix: "edge"
|
||||
models:
|
||||
package: internal/web/models
|
||||
|
||||
|
||||
fields:
|
||||
bool: [ "uamIsOn", "followPort", "requestHostExcludingPort", "autoRemoteStart", "autoInstallNftables", "enableIPLists", "detectAgents", "checkingPorts", "enableRecordHealthCheck", "offlineIsNotified", "http2Enabled", "http3Enabled", "enableHTTP2", "retry50X", "retry40X", "autoSystemTuning", "disableDefaultDB", "autoTrimDisks" ]
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,3 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
go run `dirname $0`/../cmd/sql-dump/main.go -dir=`dirname $0`
|
||||
# generate 'internal/setup/sql.json' file
|
||||
|
||||
CWD="$(dirname "$0")"
|
||||
|
||||
go run "${CWD}"/../cmd/sql-dump/main.go -dir="${CWD}"
|
||||
@@ -2,8 +2,10 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/apps"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/configs"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/nodes"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/setup"
|
||||
@@ -11,23 +13,30 @@ import (
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
"github.com/iwind/TeaGo/maps"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"github.com/iwind/gosock/pkg/gosock"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if !Tea.IsTesting() {
|
||||
Tea.Env = "prod"
|
||||
}
|
||||
app := apps.NewAppCmd()
|
||||
var app = apps.NewAppCmd()
|
||||
app.Version(teaconst.Version)
|
||||
app.Product(teaconst.ProductName)
|
||||
app.Usage(teaconst.ProcessName + " [start|stop|restart|setup|upgrade|service|daemon]")
|
||||
app.Usage(teaconst.ProcessName + " [-h|-v|start|stop|restart|setup|upgrade|service|daemon|issues]")
|
||||
|
||||
// 短版本号
|
||||
app.On("-V", func() {
|
||||
_, _ = os.Stdout.WriteString(teaconst.Version)
|
||||
})
|
||||
app.On("setup", func() {
|
||||
setupCmd := setup.NewSetupFromCmd()
|
||||
var setupCmd = setup.NewSetupFromCmd()
|
||||
err := setupCmd.Run()
|
||||
result := maps.Map{}
|
||||
var result = maps.Map{}
|
||||
if err != nil {
|
||||
result["isOk"] = false
|
||||
result["error"] = err.Error()
|
||||
@@ -69,6 +78,14 @@ func main() {
|
||||
}
|
||||
fmt.Println("done")
|
||||
})
|
||||
app.On("reset", func() {
|
||||
err := configs.ResetAPIConfig()
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]reset failed: " + err.Error())
|
||||
return
|
||||
}
|
||||
fmt.Println("done")
|
||||
})
|
||||
app.On("goman", func() {
|
||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||
reply, err := sock.Send(&gosock.Command{Code: "goman"})
|
||||
@@ -97,6 +114,114 @@ func main() {
|
||||
}
|
||||
}
|
||||
})
|
||||
app.On("db.stmt.prepare", func() {
|
||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||
reply, err := sock.Send(&gosock.Command{Code: "db.stmt.prepare"})
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
} else {
|
||||
var isOn = maps.NewMap(reply.Params).GetBool("isOn")
|
||||
if isOn {
|
||||
fmt.Println("show statements: on")
|
||||
} else {
|
||||
fmt.Println("show statements: off")
|
||||
}
|
||||
}
|
||||
})
|
||||
app.On("db.stmt.count", func() {
|
||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||
reply, err := sock.Send(&gosock.Command{Code: "db.stmt.count"})
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
} else {
|
||||
var count = maps.NewMap(reply.Params).GetInt("count")
|
||||
fmt.Println("prepared statements count: " + types.String(count))
|
||||
}
|
||||
})
|
||||
app.On("issues", func() {
|
||||
var flagSet = flag.NewFlagSet("issues", flag.ExitOnError)
|
||||
var formatJSON = false
|
||||
flagSet.BoolVar(&formatJSON, "json", false, "")
|
||||
_ = flagSet.Parse(os.Args[2:])
|
||||
|
||||
data, err := os.ReadFile(Tea.LogFile("issues.log"))
|
||||
if err != nil {
|
||||
if formatJSON {
|
||||
fmt.Print("[]")
|
||||
} else {
|
||||
fmt.Println("no issues yet")
|
||||
}
|
||||
} else {
|
||||
var issueMaps = []maps.Map{}
|
||||
err = json.Unmarshal(data, &issueMaps)
|
||||
if err != nil {
|
||||
if formatJSON {
|
||||
fmt.Print("[]")
|
||||
} else {
|
||||
fmt.Println("no issues yet")
|
||||
}
|
||||
} else {
|
||||
if formatJSON {
|
||||
fmt.Print(string(data))
|
||||
} else {
|
||||
if len(issueMaps) == 0 {
|
||||
fmt.Println("no issues yet")
|
||||
} else {
|
||||
for i, issue := range issueMaps {
|
||||
fmt.Println("issue " + types.String(i+1) + ": " + issue.GetString("message"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
app.On("instance", func() {
|
||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||
reply, err := sock.Send(&gosock.Command{Code: "instance"})
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
} else {
|
||||
replyJSON, err := json.MarshalIndent(reply.Params, "", " ")
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]marshal result failed: " + err.Error())
|
||||
} else {
|
||||
fmt.Println(string(replyJSON))
|
||||
}
|
||||
}
|
||||
})
|
||||
app.On("token", func() {
|
||||
var role = ""
|
||||
if len(os.Args) <= 2 {
|
||||
fmt.Println("require --role parameter")
|
||||
return
|
||||
}
|
||||
|
||||
var set = flag.NewFlagSet("", flag.ExitOnError)
|
||||
set.StringVar(&role, "role", "", "edge-api token --role=[admin|user|api]")
|
||||
_ = set.Parse(os.Args[2:])
|
||||
|
||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||
reply, err := sock.Send(&gosock.Command{Code: "lookupToken", Params: map[string]any{
|
||||
"role": role,
|
||||
}})
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
} else {
|
||||
var resultMap = maps.NewMap(reply.Params)
|
||||
if resultMap.GetBool("isOk") {
|
||||
var tokens = resultMap.GetSlice("tokens")
|
||||
fmt.Printf("%-35s | %-35s\n", "nodeId", "secret")
|
||||
fmt.Println(strings.Repeat("-", 70))
|
||||
for _, tokenMap := range tokens {
|
||||
var m = maps.NewMap(tokenMap)
|
||||
fmt.Printf("%-35s | %-35s\n", m.GetString("nodeId"), m.GetString("secret"))
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[ERROR]" + resultMap.GetString("err"))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
app.Run(func() {
|
||||
nodes.NewAPINode().Start()
|
||||
})
|
||||
|
||||
2
cmd/edge-instance-installer/.gitignore
vendored
Normal file
2
cmd/edge-instance-installer/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
edge-instance-installer*
|
||||
prepare.sh
|
||||
45
cmd/edge-instance-installer/build.sh
Executable file
45
cmd/edge-instance-installer/build.sh
Executable file
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function build() {
|
||||
ROOT=$(dirname "$0")
|
||||
|
||||
OS="${1}"
|
||||
ARCH="${2}"
|
||||
TAG="${3}"
|
||||
|
||||
if [ -z "$OS" ]; then
|
||||
echo "usage: build.sh OS ARCH"
|
||||
exit
|
||||
fi
|
||||
|
||||
if [ -z "$ARCH" ]; then
|
||||
echo "usage: build.sh OS ARCH"
|
||||
exit
|
||||
fi
|
||||
|
||||
VERSION=$(lookup_version "${ROOT}/../../internal/const/const.go")
|
||||
TARGET_NAME="edge-instance-installer-${OS}-${ARCH}-v${VERSION}"
|
||||
|
||||
env GOOS=linux GOARCH="${ARCH}" go build -tags="${TAG}" -trimpath -ldflags="-s -w" -o "${TARGET_NAME}" main.go
|
||||
|
||||
if [ -f "${TARGET_NAME}" ]; then
|
||||
cp "${TARGET_NAME}" "${ROOT}/../../../EdgeAdmin/docker/instance/edge-instance/assets"
|
||||
fi
|
||||
|
||||
echo "[done]"
|
||||
}
|
||||
|
||||
function lookup_version() {
|
||||
FILE=$1
|
||||
VERSION_DATA=$(cat "$FILE")
|
||||
re="Version[ ]+=[ ]+\"([0-9.]+)\""
|
||||
if [[ $VERSION_DATA =~ $re ]]; then
|
||||
VERSION=${BASH_REMATCH[1]}
|
||||
echo "$VERSION"
|
||||
else
|
||||
echo "could not match version"
|
||||
exit
|
||||
fi
|
||||
}
|
||||
|
||||
build "$1" "$2" "$3"
|
||||
97
cmd/edge-instance-installer/main.go
Normal file
97
cmd/edge-instance-installer/main.go
Normal file
@@ -0,0 +1,97 @@
|
||||
// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/instances"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
"github.com/iwind/TeaGo/lists"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var verbose = lists.ContainsString(os.Args, "-v")
|
||||
|
||||
var dbHost = "127.0.0.1"
|
||||
var dbPassword = "123456"
|
||||
var dbName = "edges"
|
||||
|
||||
envDBHost, _ := os.LookupEnv("EDGE_DB_HOST")
|
||||
if len(envDBHost) > 0 {
|
||||
dbHost = envDBHost
|
||||
if verbose {
|
||||
log.Println("env EDGE_DB_HOST=" + envDBHost)
|
||||
}
|
||||
}
|
||||
|
||||
envDBPassword, _ := os.LookupEnv("EDGE_DB_PASSWORD")
|
||||
if len(envDBPassword) > 0 {
|
||||
dbPassword = envDBPassword
|
||||
if verbose {
|
||||
log.Println("env EDGE_DB_PASSWORD=" + envDBPassword)
|
||||
}
|
||||
}
|
||||
|
||||
envDBName, _ := os.LookupEnv("EDGE_DB_NAME")
|
||||
if len(envDBName) > 0 {
|
||||
dbName = envDBName
|
||||
if verbose {
|
||||
log.Println("env EDGE_DB_NAME=" + envDBName)
|
||||
}
|
||||
}
|
||||
|
||||
var isTesting = lists.ContainsString(os.Args, "-test") || lists.ContainsString(os.Args, "--test")
|
||||
if isTesting {
|
||||
fmt.Println("testing mode ...")
|
||||
}
|
||||
|
||||
var instance = instances.NewInstance(instances.Options{
|
||||
IsTesting: isTesting,
|
||||
Verbose: verbose,
|
||||
Cacheable: false,
|
||||
WorkDir: "",
|
||||
SrcDir: "/usr/local/goedge/src",
|
||||
DB: struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
Name string
|
||||
}{
|
||||
Host: dbHost,
|
||||
Port: 3306,
|
||||
Username: "root",
|
||||
Password: dbPassword,
|
||||
Name: dbName,
|
||||
},
|
||||
AdminNode: struct {
|
||||
Port int
|
||||
}{
|
||||
Port: 7788,
|
||||
},
|
||||
APINode: struct {
|
||||
HTTPPort int
|
||||
RestHTTPPort int
|
||||
}{
|
||||
HTTPPort: 8001,
|
||||
RestHTTPPort: 8002,
|
||||
},
|
||||
Node: struct{ HTTPPort int }{
|
||||
HTTPPort: 80,
|
||||
},
|
||||
UserNode: struct {
|
||||
HTTPPort int
|
||||
}{
|
||||
HTTPPort: 7799,
|
||||
},
|
||||
})
|
||||
err := instance.SetupAll()
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]setup failed: " + err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("ok")
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/installers/helpers"
|
||||
"github.com/iwind/gosock/pkg/gosock"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -51,7 +51,7 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
unzip := utils.NewUnzip(zipPath, targetPath)
|
||||
unzip := helpers.NewUnzip(zipPath, targetPath)
|
||||
err := unzip.Run()
|
||||
if err != nil {
|
||||
stderr("ERROR: " + err.Error())
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package main
|
||||
|
||||
// 注意这里的依赖文件应该最小化,从而使编译后的文件最小化
|
||||
import (
|
||||
"flag"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/installers/helpers"
|
||||
"github.com/iwind/gosock/pkg/gosock"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -51,7 +52,7 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
unzip := utils.NewUnzip(zipPath, targetPath)
|
||||
var unzip = helpers.NewUnzip(zipPath, targetPath)
|
||||
err := unzip.Run()
|
||||
if err != nil {
|
||||
stderr("ERROR: " + err.Error())
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models/regions"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"github.com/iwind/TeaGo/lists"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 导入数据
|
||||
if lists.ContainsString(os.Args, "import") {
|
||||
dbs.NotifyReady()
|
||||
|
||||
data, err := ioutil.ReadFile(Tea.Root + "/resources/ipdata/ip2region/global_region.csv")
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if len(data) == 0 {
|
||||
logs.Println("[ERROR]file content should not be empty")
|
||||
return
|
||||
}
|
||||
lines := bytes.Split(data, []byte{'\n'})
|
||||
for _, line := range lines {
|
||||
line = bytes.TrimSpace(line)
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
s := string(line)
|
||||
reg := regexp.MustCompile(`(?U)(\d+),(\d+),(.+),(\d+),`)
|
||||
if !reg.MatchString(s) {
|
||||
continue
|
||||
}
|
||||
result := reg.FindStringSubmatch(s)
|
||||
dataId := result[1]
|
||||
parentDataId := result[2]
|
||||
name := result[3]
|
||||
level := result[4]
|
||||
|
||||
switch level {
|
||||
case "1": // 国家|地区
|
||||
countryId, err := regions.SharedRegionCountryDAO.FindCountryIdWithDataId(nil, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if countryId == 0 {
|
||||
logs.Println("creating country or region ", name)
|
||||
_, err = regions.SharedRegionCountryDAO.CreateCountry(nil, name, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
case "2": // 省份|地区
|
||||
provinceId, err := regions.SharedRegionProvinceDAO.FindProvinceIdWithDataId(nil, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if provinceId == 0 {
|
||||
logs.Println("creating province", name)
|
||||
|
||||
countryId, err := regions.SharedRegionCountryDAO.FindCountryIdWithDataId(nil, parentDataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if countryId == 0 {
|
||||
logs.Println("[ERROR]can not find country from data id '" + parentDataId + "'")
|
||||
return
|
||||
}
|
||||
|
||||
_, err = regions.SharedRegionProvinceDAO.CreateProvince(nil, countryId, name, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
case "3": // 城市
|
||||
cityId, err := regions.SharedRegionCityDAO.FindCityWithDataId(nil, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if cityId == 0 {
|
||||
logs.Println("creating city", name)
|
||||
|
||||
provinceId, err := regions.SharedRegionProvinceDAO.FindProvinceIdWithDataId(nil, parentDataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
_, err = regions.SharedRegionCityDAO.CreateCity(nil, provinceId, name, dataId)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logs.Println("done")
|
||||
}
|
||||
|
||||
// 检查数据
|
||||
if lists.ContainsString(os.Args, "check") {
|
||||
dbs.NotifyReady()
|
||||
|
||||
data, err := ioutil.ReadFile(Tea.Root + "/resources/ipdata/ip2region/ip.merge.txt")
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if len(data) == 0 {
|
||||
logs.Println("[ERROR]file should not be empty")
|
||||
return
|
||||
}
|
||||
lines := bytes.Split(data, []byte("\n"))
|
||||
for index, line := range lines {
|
||||
s := string(bytes.TrimSpace(line))
|
||||
if len(s) == 0 {
|
||||
continue
|
||||
}
|
||||
pieces := strings.Split(s, "|")
|
||||
countryName := pieces[2]
|
||||
provinceName := pieces[4]
|
||||
providerName := pieces[6]
|
||||
|
||||
// 记录provider
|
||||
if len(providerName) > 0 && providerName != "0" {
|
||||
providerId, err := regions.SharedRegionProviderDAO.FindProviderIdWithNameCacheable(nil, providerName)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]find provider id failed: " + err.Error())
|
||||
return
|
||||
}
|
||||
if providerId == 0 {
|
||||
logs.Println("creating new provider '"+providerName+"' ... ", index, "line")
|
||||
_, err = regions.SharedRegionProviderDAO.CreateProvider(nil, providerName)
|
||||
if err != nil {
|
||||
logs.Println("create new provider failed: " + providerName)
|
||||
return
|
||||
}
|
||||
logs.Println("created new provider '" + providerName + "'")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if lists.ContainsString([]string{"0", "欧洲", "北美地区", "法国南部领地", "非洲地区", "亚太地区"}, countryName) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查国家
|
||||
countryId, err := regions.SharedRegionCountryDAO.FindCountryIdWithNameCacheable(nil, countryName)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if countryId == 0 {
|
||||
logs.Println("[ERROR]can not find country '"+countryName+"', index: ", index, "data: "+s)
|
||||
return
|
||||
}
|
||||
|
||||
// 检查省份
|
||||
if countryName == "中国" {
|
||||
if lists.ContainsString([]string{"0"}, provinceName) {
|
||||
continue
|
||||
}
|
||||
|
||||
provinceId, err := regions.SharedRegionProvinceDAO.FindProvinceIdWithNameCacheable(nil, countryId, provinceName)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
if provinceId == 0 {
|
||||
logs.Println("[ERROR]can not find province '"+provinceName+"', index: ", index, "data: "+s)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logs.Println("done")
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/setup"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"go/format"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -19,58 +17,25 @@ func main() {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
results, err := setup.NewSQLDump().Dump(db)
|
||||
results, err := setup.NewSQLDump().Dump(db, true)
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
resultsJSON, err := json.Marshal(results)
|
||||
|
||||
prettyResultsJSON, err := json.MarshalIndent(results, "", " ")
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
dir, _ := os.Getwd()
|
||||
var sqlFile string
|
||||
for i := 0; i < 5; i++ {
|
||||
lookupFile := dir + "/internal/setup/sql.go"
|
||||
_, err = os.Stat(lookupFile)
|
||||
if err != nil {
|
||||
dir = filepath.Dir(dir)
|
||||
continue
|
||||
}
|
||||
sqlFile = lookupFile
|
||||
}
|
||||
|
||||
if len(sqlFile) == 0 {
|
||||
fmt.Println("[ERROR]can not find sql.go")
|
||||
return
|
||||
}
|
||||
content := []byte(`package setup
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
)
|
||||
|
||||
// 最新版本的数据库SQL语句,用来对比并升级已有的数据库
|
||||
// 由 sql-dump/main.go 自动生成
|
||||
func init() {
|
||||
err := json.Unmarshal([]byte(` + strconv.Quote(string(resultsJSON)) + `), LatestSQLResult)
|
||||
// 写入到 sql.json 中
|
||||
var dir = filepath.Dir(Tea.Root)
|
||||
err = os.WriteFile(dir+"/internal/setup/sql.json", prettyResultsJSON, 0666)
|
||||
if err != nil {
|
||||
logs.Println("[ERROR]load sql failed: " + err.Error())
|
||||
}
|
||||
}
|
||||
`)
|
||||
dst, err := format.Source(content)
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]format code failed: " + err.Error())
|
||||
fmt.Println("[ERROR]" + err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = ioutil.WriteFile(sqlFile, dst, 0666)
|
||||
if err != nil {
|
||||
fmt.Println("[ERROR]write file failed: " + err.Error())
|
||||
return
|
||||
}
|
||||
fmt.Println("ok")
|
||||
}
|
||||
|
||||
3
dist/.gitignore
vendored
3
dist/.gitignore
vendored
@@ -1 +1,2 @@
|
||||
*.zip
|
||||
*.zip
|
||||
edge-api
|
||||
75
go.mod
75
go.mod
@@ -1,27 +1,70 @@
|
||||
module github.com/TeaOSLab/EdgeAPI
|
||||
|
||||
go 1.15
|
||||
go 1.21
|
||||
|
||||
replace github.com/TeaOSLab/EdgeCommon => ../EdgeCommon
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.8.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/dns/armdns v1.1.0
|
||||
github.com/TeaOSLab/EdgeCommon v0.0.0-00010101000000-000000000000
|
||||
github.com/aliyun/alibaba-cloud-sdk-go v1.61.1183
|
||||
github.com/aliyun/alibaba-cloud-sdk-go v1.62.587
|
||||
github.com/andybalholm/brotli v1.0.4
|
||||
github.com/cespare/xxhash/v2 v2.1.1
|
||||
github.com/go-acme/lego/v4 v4.5.2
|
||||
github.com/go-sql-driver/mysql v1.5.0
|
||||
github.com/golang/protobuf v1.5.2
|
||||
github.com/iwind/TeaGo v0.0.0-20220304043459-0dd944a5b475
|
||||
github.com/iwind/gosock v0.0.0-20210722083328-12b2d66abec3
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/aws/aws-sdk-go v1.40.45
|
||||
github.com/cespare/xxhash v1.1.0
|
||||
github.com/fsnotify/fsnotify v1.6.0
|
||||
github.com/go-acme/lego/v4 v4.10.2
|
||||
github.com/go-sql-driver/mysql v1.7.0
|
||||
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible
|
||||
github.com/iwind/TeaGo v0.0.0-20240312020455-6f20b5121caf
|
||||
github.com/iwind/gosock v0.0.0-20220505115348-f88412125a62
|
||||
github.com/miekg/dns v1.1.50
|
||||
github.com/mozillazg/go-pinyin v0.18.0
|
||||
github.com/pkg/sftp v1.12.0
|
||||
github.com/shirou/gopsutil/v3 v3.22.2 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.2 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292
|
||||
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8
|
||||
google.golang.org/grpc v1.45.0
|
||||
google.golang.org/protobuf v1.27.1
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
|
||||
github.com/shirou/gopsutil/v3 v3.22.2
|
||||
github.com/smartwalle/alipay/v3 v3.2.20
|
||||
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.801
|
||||
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod v1.0.801
|
||||
github.com/volcengine/volc-sdk-golang v1.0.124
|
||||
golang.org/x/crypto v0.22.0
|
||||
golang.org/x/net v0.24.0
|
||||
golang.org/x/sys v0.19.0
|
||||
google.golang.org/grpc v1.62.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.1.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.2.0 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.1-0.20220228012449-10b1cf09e00b // indirect
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/smartwalle/ncrypto v1.0.4 // indirect
|
||||
github.com/smartwalle/ngx v1.0.9 // indirect
|
||||
github.com/smartwalle/nsign v1.0.9 // indirect
|
||||
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.9 // indirect
|
||||
github.com/tklauser/numcpus v0.3.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.2 // indirect
|
||||
golang.org/x/mod v0.8.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
golang.org/x/tools v0.6.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240228224816-df926f6c8641 // indirect
|
||||
google.golang.org/protobuf v1.33.0 // indirect
|
||||
gopkg.in/ini.v1 v1.66.6 // indirect
|
||||
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BaseStorage struct {
|
||||
isOk bool
|
||||
version int
|
||||
}
|
||||
|
||||
func (this *BaseStorage) SetVersion(version int) {
|
||||
this.version = version
|
||||
}
|
||||
|
||||
func (this *BaseStorage) Version() int {
|
||||
return this.version
|
||||
}
|
||||
|
||||
func (this *BaseStorage) IsOk() bool {
|
||||
return this.isOk
|
||||
}
|
||||
|
||||
func (this *BaseStorage) SetOk(isOk bool) {
|
||||
this.isOk = isOk
|
||||
}
|
||||
|
||||
// Marshal 对日志进行编码
|
||||
func (this *BaseStorage) Marshal(accessLog *pb.HTTPAccessLog) ([]byte, error) {
|
||||
return json.Marshal(accessLog)
|
||||
}
|
||||
|
||||
// FormatVariables 格式化字符串中的变量
|
||||
func (this *BaseStorage) FormatVariables(s string) string {
|
||||
now := time.Now()
|
||||
return configutils.ParseVariables(s, func(varName string) (value string) {
|
||||
switch varName {
|
||||
case "year":
|
||||
return strconv.Itoa(now.Year())
|
||||
case "month":
|
||||
return fmt.Sprintf("%02d", now.Month())
|
||||
case "week":
|
||||
_, week := now.ISOWeek()
|
||||
return fmt.Sprintf("%02d", week)
|
||||
case "day":
|
||||
return fmt.Sprintf("%02d", now.Day())
|
||||
case "hour":
|
||||
return fmt.Sprintf("%02d", now.Hour())
|
||||
case "minute":
|
||||
return fmt.Sprintf("%02d", now.Minute())
|
||||
case "second":
|
||||
return fmt.Sprintf("%02d", now.Second())
|
||||
case "date":
|
||||
return fmt.Sprintf("%d%02d%02d", now.Year(), now.Month(), now.Day())
|
||||
}
|
||||
|
||||
return varName
|
||||
})
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"os/exec"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// CommandStorage 通过命令行存储
|
||||
type CommandStorage struct {
|
||||
BaseStorage
|
||||
|
||||
config *serverconfigs.AccessLogCommandStorageConfig
|
||||
|
||||
writeLocker sync.Mutex
|
||||
}
|
||||
|
||||
func NewCommandStorage(config *serverconfigs.AccessLogCommandStorageConfig) *CommandStorage {
|
||||
return &CommandStorage{config: config}
|
||||
}
|
||||
|
||||
func (this *CommandStorage) Config() interface{} {
|
||||
return this.config
|
||||
}
|
||||
|
||||
// Start 启动
|
||||
func (this *CommandStorage) Start() error {
|
||||
if len(this.config.Command) == 0 {
|
||||
return errors.New("'command' should not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 写入日志
|
||||
func (this *CommandStorage) Write(accessLogs []*pb.HTTPAccessLog) error {
|
||||
if len(accessLogs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
this.writeLocker.Lock()
|
||||
defer this.writeLocker.Unlock()
|
||||
|
||||
cmd := exec.Command(this.config.Command, this.config.Args...)
|
||||
if len(this.config.Dir) > 0 {
|
||||
cmd.Dir = this.config.Dir
|
||||
}
|
||||
|
||||
stdout := bytes.NewBuffer([]byte{})
|
||||
cmd.Stdout = stdout
|
||||
|
||||
w, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, accessLog := range accessLogs {
|
||||
data, err := this.Marshal(accessLog)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
continue
|
||||
}
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
|
||||
_, err = w.Write([]byte("\n"))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
}
|
||||
_ = w.Close()
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
|
||||
if stdout.Len() > 0 {
|
||||
logs.Error(errors.New(string(stdout.Bytes())))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭
|
||||
func (this *CommandStorage) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCommandStorage_Write(t *testing.T) {
|
||||
php, err := exec.LookPath("php")
|
||||
if err != nil { // not found php, so we can not test
|
||||
t.Log("php:", err)
|
||||
return
|
||||
}
|
||||
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
before := time.Now()
|
||||
|
||||
storage := NewCommandStorage(&serverconfigs.AccessLogCommandStorageConfig{
|
||||
Command: php,
|
||||
Args: []string{cwd + "/tests/command_storage.php"},
|
||||
})
|
||||
err = storage.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/hello",
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/world",
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/lu",
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/ping",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = storage.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Log(time.Since(before).Seconds(), "seconds")
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ESStorage ElasticSearch存储策略
|
||||
type ESStorage struct {
|
||||
BaseStorage
|
||||
|
||||
config *serverconfigs.AccessLogESStorageConfig
|
||||
}
|
||||
|
||||
func NewESStorage(config *serverconfigs.AccessLogESStorageConfig) *ESStorage {
|
||||
return &ESStorage{config: config}
|
||||
}
|
||||
|
||||
func (this *ESStorage) Config() interface{} {
|
||||
return this.config
|
||||
}
|
||||
|
||||
// Start 开启
|
||||
func (this *ESStorage) Start() error {
|
||||
if len(this.config.Endpoint) == 0 {
|
||||
return errors.New("'endpoint' should not be nil")
|
||||
}
|
||||
if !regexp.MustCompile(`(?i)^(http|https)://`).MatchString(this.config.Endpoint) {
|
||||
this.config.Endpoint = "http://" + this.config.Endpoint
|
||||
}
|
||||
if len(this.config.Index) == 0 {
|
||||
return errors.New("'index' should not be nil")
|
||||
}
|
||||
if len(this.config.MappingType) == 0 {
|
||||
return errors.New("'mappingType' should not be nil")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 写入日志
|
||||
func (this *ESStorage) Write(accessLogs []*pb.HTTPAccessLog) error {
|
||||
if len(accessLogs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
bulk := &strings.Builder{}
|
||||
indexName := this.FormatVariables(this.config.Index)
|
||||
typeName := this.FormatVariables(this.config.MappingType)
|
||||
for _, accessLog := range accessLogs {
|
||||
if len(accessLog.RequestId) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
opData, err := json.Marshal(map[string]interface{}{
|
||||
"index": map[string]interface{}{
|
||||
"_index": indexName,
|
||||
"_type": typeName,
|
||||
"_id": accessLog.RequestId,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_ES_STORAGE", "write failed: "+err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := this.Marshal(accessLog)
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_ES_STORAGE", "marshal data failed: "+err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
bulk.Write(opData)
|
||||
bulk.WriteString("\n")
|
||||
bulk.Write(data)
|
||||
bulk.WriteString("\n")
|
||||
}
|
||||
|
||||
if bulk.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, this.config.Endpoint+"/_bulk", strings.NewReader(bulk.String()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", strings.ReplaceAll(teaconst.ProductName, " ", "-")+"/"+teaconst.Version)
|
||||
if len(this.config.Username) > 0 || len(this.config.Password) > 0 {
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(this.config.Username+":"+this.config.Password)))
|
||||
}
|
||||
client := utils.SharedHttpClient(10 * time.Second)
|
||||
defer func() {
|
||||
_ = req.Body.Close()
|
||||
}()
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyData, _ := ioutil.ReadAll(resp.Body)
|
||||
return errors.New("ElasticSearch response status code: " + fmt.Sprintf("%d", resp.StatusCode) + " content: " + string(bodyData))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭
|
||||
func (this *ESStorage) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestESStorage_Write(t *testing.T) {
|
||||
storage := NewESStorage(&serverconfigs.AccessLogESStorageConfig{
|
||||
Endpoint: "http://127.0.0.1:9200",
|
||||
Index: "logs",
|
||||
MappingType: "accessLogs",
|
||||
Username: "hello",
|
||||
Password: "world",
|
||||
})
|
||||
err := storage.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
{
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestMethod: "POST",
|
||||
RequestPath: "/1",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
TimeISO8601: "2018-07-23T22:23:35+08:00",
|
||||
Header: map[string]*pb.Strings{
|
||||
"Content-Type": {Values: []string{"text/html"}},
|
||||
},
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/2",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
TimeISO8601: "2018-07-23T22:23:35+08:00",
|
||||
Header: map[string]*pb.Strings{
|
||||
"Content-Type": {Values: []string{"text/css"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
err = storage.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// FileStorage 文件存储策略
|
||||
type FileStorage struct {
|
||||
BaseStorage
|
||||
|
||||
config *serverconfigs.AccessLogFileStorageConfig
|
||||
|
||||
writeLocker sync.Mutex
|
||||
|
||||
files map[string]*os.File // path => *File
|
||||
filesLocker sync.Mutex
|
||||
}
|
||||
|
||||
func NewFileStorage(config *serverconfigs.AccessLogFileStorageConfig) *FileStorage {
|
||||
return &FileStorage{
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
func (this *FileStorage) Config() interface{} {
|
||||
return this.config
|
||||
}
|
||||
|
||||
// Start 开启
|
||||
func (this *FileStorage) Start() error {
|
||||
if len(this.config.Path) == 0 {
|
||||
return errors.New("'path' should not be empty")
|
||||
}
|
||||
|
||||
this.files = map[string]*os.File{}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write 写入日志
|
||||
func (this *FileStorage) Write(accessLogs []*pb.HTTPAccessLog) error {
|
||||
if len(accessLogs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
fp := this.fp()
|
||||
if fp == nil {
|
||||
return errors.New("file pointer should not be nil")
|
||||
}
|
||||
this.writeLocker.Lock()
|
||||
defer this.writeLocker.Unlock()
|
||||
|
||||
for _, accessLog := range accessLogs {
|
||||
data, err := this.Marshal(accessLog)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
continue
|
||||
}
|
||||
_, err = fp.Write(data)
|
||||
if err != nil {
|
||||
_ = this.Close()
|
||||
break
|
||||
}
|
||||
_, _ = fp.WriteString("\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭
|
||||
func (this *FileStorage) Close() error {
|
||||
this.filesLocker.Lock()
|
||||
defer this.filesLocker.Unlock()
|
||||
|
||||
var resultErr error
|
||||
for _, f := range this.files {
|
||||
err := f.Close()
|
||||
if err != nil {
|
||||
resultErr = err
|
||||
}
|
||||
}
|
||||
return resultErr
|
||||
}
|
||||
|
||||
func (this *FileStorage) fp() *os.File {
|
||||
path := this.FormatVariables(this.config.Path)
|
||||
|
||||
this.filesLocker.Lock()
|
||||
defer this.filesLocker.Unlock()
|
||||
fp, ok := this.files[path]
|
||||
if ok {
|
||||
return fp
|
||||
}
|
||||
|
||||
// 关闭其他的文件
|
||||
for _, f := range this.files {
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
// 是否创建文件目录
|
||||
if this.config.AutoCreate {
|
||||
dir := filepath.Dir(path)
|
||||
_, err := os.Stat(dir)
|
||||
if os.IsNotExist(err) {
|
||||
err = os.MkdirAll(dir, 0777)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 打开新文件
|
||||
fp, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return nil
|
||||
}
|
||||
this.files[path] = fp
|
||||
|
||||
return fp
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileStorage_Write(t *testing.T) {
|
||||
storage := NewFileStorage(&serverconfigs.AccessLogFileStorageConfig{
|
||||
Path: Tea.Root + "/logs/access-${date}.log",
|
||||
})
|
||||
err := storage.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
{
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestPath: "/hello",
|
||||
},
|
||||
{
|
||||
RequestPath: "/world",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestPath: "/1",
|
||||
},
|
||||
{
|
||||
RequestPath: "/2",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestMethod: "POST",
|
||||
RequestPath: "/1",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/2",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
err = storage.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||
|
||||
package accesslogs
|
||||
|
||||
import "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
|
||||
// StorageInterface 日志存储接口
|
||||
type StorageInterface interface {
|
||||
// Version 获取版本
|
||||
Version() int
|
||||
|
||||
// SetVersion 设置版本
|
||||
SetVersion(version int)
|
||||
|
||||
IsOk() bool
|
||||
|
||||
SetOk(ok bool)
|
||||
|
||||
// Config 获取配置
|
||||
Config() interface{}
|
||||
|
||||
// Start 开启
|
||||
Start() error
|
||||
|
||||
// Write 写入日志
|
||||
Write(accessLogs []*pb.HTTPAccessLog) error
|
||||
|
||||
// Close 关闭
|
||||
Close() error
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/lists"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var SharedStorageManager = NewStorageManager()
|
||||
|
||||
type StorageManager struct {
|
||||
storageMap map[int64]StorageInterface // policyId => Storage
|
||||
|
||||
locker sync.Mutex
|
||||
}
|
||||
|
||||
func NewStorageManager() *StorageManager {
|
||||
return &StorageManager{
|
||||
storageMap: map[int64]StorageInterface{},
|
||||
}
|
||||
}
|
||||
|
||||
func (this *StorageManager) Start() {
|
||||
var ticker = time.NewTicker(1 * time.Minute)
|
||||
if Tea.IsTesting() {
|
||||
ticker = time.NewTicker(5 * time.Second)
|
||||
}
|
||||
|
||||
// 启动时执行一次
|
||||
var err = this.Loop()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "update error: "+err.Error())
|
||||
}
|
||||
|
||||
// 循环执行
|
||||
for range ticker.C {
|
||||
err := this.Loop()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "update error: "+err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Loop 更新
|
||||
func (this *StorageManager) Loop() error {
|
||||
policies, err := models.SharedHTTPAccessLogPolicyDAO.FindAllEnabledAndOnPolicies(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var policyIds = []int64{}
|
||||
for _, policy := range policies {
|
||||
if policy.IsOn == 1 {
|
||||
policyIds = append(policyIds, int64(policy.Id))
|
||||
}
|
||||
}
|
||||
|
||||
this.locker.Lock()
|
||||
defer this.locker.Unlock()
|
||||
|
||||
// 关闭不用的
|
||||
for policyId, storage := range this.storageMap {
|
||||
if !lists.ContainsInt64(policyIds, policyId) {
|
||||
err := storage.Close()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "close '"+types.String(policyId)+"' failed: "+err.Error())
|
||||
}
|
||||
delete(this.storageMap, policyId)
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "remove '"+types.String(policyId)+"'")
|
||||
}
|
||||
}
|
||||
|
||||
for _, policy := range policies {
|
||||
var policyId = int64(policy.Id)
|
||||
storage, ok := this.storageMap[policyId]
|
||||
if ok {
|
||||
// 检查配置是否有变更
|
||||
if types.Int(policy.Version) != storage.Version() {
|
||||
err = storage.Close()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "close policy '"+types.String(policyId)+"' failed: "+err.Error())
|
||||
|
||||
// 继续往下执行
|
||||
}
|
||||
|
||||
if len(policy.Options) > 0 {
|
||||
err = json.Unmarshal([]byte(policy.Options), storage.Config())
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "unmarshal policy '"+types.String(policyId)+"' config failed: "+err.Error())
|
||||
storage.SetOk(false)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
storage.SetVersion(types.Int(policy.Version))
|
||||
err := storage.Start()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "start policy '"+types.String(policyId)+"' failed: "+err.Error())
|
||||
continue
|
||||
}
|
||||
storage.SetOk(true)
|
||||
remotelogs.Println("ACCESS_LOG_STORAGE_MANAGER", "restart policy '"+types.String(policyId)+"'")
|
||||
}
|
||||
} else {
|
||||
storage, err := this.createStorage(policy.Type, []byte(policy.Options))
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "create policy '"+types.String(policyId)+"' failed: "+err.Error())
|
||||
continue
|
||||
}
|
||||
storage.SetVersion(types.Int(policy.Version))
|
||||
this.storageMap[policyId] = storage
|
||||
err = storage.Start()
|
||||
if err != nil {
|
||||
remotelogs.Error("ACCESS_LOG_STORAGE_MANAGER", "start policy '"+types.String(policyId)+"' failed: "+err.Error())
|
||||
continue
|
||||
}
|
||||
storage.SetOk(true)
|
||||
remotelogs.Println("ACCESS_LOG_STORAGE_MANAGER", "start policy '"+types.String(policyId)+"'")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (this *StorageManager) createStorage(storageType string, optionsJSON []byte) (StorageInterface, error) {
|
||||
switch storageType {
|
||||
case serverconfigs.AccessLogStorageTypeFile:
|
||||
var config = &serverconfigs.AccessLogFileStorageConfig{}
|
||||
if len(optionsJSON) > 0 {
|
||||
err := json.Unmarshal(optionsJSON, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewFileStorage(config), nil
|
||||
case serverconfigs.AccessLogStorageTypeES:
|
||||
var config = &serverconfigs.AccessLogESStorageConfig{}
|
||||
if len(optionsJSON) > 0 {
|
||||
err := json.Unmarshal(optionsJSON, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewESStorage(config), nil
|
||||
case serverconfigs.AccessLogStorageTypeTCP:
|
||||
var config = &serverconfigs.AccessLogTCPStorageConfig{}
|
||||
if len(optionsJSON) > 0 {
|
||||
err := json.Unmarshal(optionsJSON, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewTCPStorage(config), nil
|
||||
case serverconfigs.AccessLogStorageTypeSyslog:
|
||||
var config = &serverconfigs.AccessLogSyslogStorageConfig{}
|
||||
if len(optionsJSON) > 0 {
|
||||
err := json.Unmarshal(optionsJSON, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewSyslogStorage(config), nil
|
||||
case serverconfigs.AccessLogStorageTypeCommand:
|
||||
var config = &serverconfigs.AccessLogCommandStorageConfig{}
|
||||
if len(optionsJSON) > 0 {
|
||||
err := json.Unmarshal(optionsJSON, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return NewCommandStorage(config), nil
|
||||
}
|
||||
|
||||
return nil, errors.New("invalid policy type '" + storageType + "'")
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStorageManager_Loop(t *testing.T) {
|
||||
dbs.NotifyReady()
|
||||
|
||||
var storage = NewStorageManager()
|
||||
err := storage.Loop()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(storage.storageMap)
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||
|
||||
//go:build !plus
|
||||
// +build !plus
|
||||
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
)
|
||||
|
||||
// 写入日志
|
||||
func (this *StorageManager) Write(policyId int64, accessLogs []*pb.HTTPAccessLog) error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type SyslogStorageProtocol = string
|
||||
|
||||
const (
|
||||
SyslogStorageProtocolTCP SyslogStorageProtocol = "tcp"
|
||||
SyslogStorageProtocolUDP SyslogStorageProtocol = "udp"
|
||||
SyslogStorageProtocolNone SyslogStorageProtocol = "none"
|
||||
SyslogStorageProtocolSocket SyslogStorageProtocol = "socket"
|
||||
)
|
||||
|
||||
type SyslogStoragePriority = int
|
||||
|
||||
// SyslogStorage syslog存储策略
|
||||
type SyslogStorage struct {
|
||||
BaseStorage
|
||||
|
||||
config *serverconfigs.AccessLogSyslogStorageConfig
|
||||
|
||||
exe string
|
||||
}
|
||||
|
||||
func NewSyslogStorage(config *serverconfigs.AccessLogSyslogStorageConfig) *SyslogStorage {
|
||||
return &SyslogStorage{config: config}
|
||||
}
|
||||
|
||||
func (this *SyslogStorage) Config() interface{} {
|
||||
return this.config
|
||||
}
|
||||
|
||||
// Start 开启
|
||||
func (this *SyslogStorage) Start() error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return errors.New("'syslog' storage only works on linux")
|
||||
}
|
||||
|
||||
exe, err := exec.LookPath("logger")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
this.exe = exe
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 写入日志
|
||||
func (this *SyslogStorage) Write(accessLogs []*pb.HTTPAccessLog) error {
|
||||
if len(accessLogs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
args := []string{}
|
||||
if len(this.config.Tag) > 0 {
|
||||
args = append(args, "-t", this.config.Tag)
|
||||
}
|
||||
|
||||
if this.config.Priority >= 0 {
|
||||
args = append(args, "-p", strconv.Itoa(this.config.Priority))
|
||||
}
|
||||
|
||||
switch this.config.Protocol {
|
||||
case SyslogStorageProtocolTCP:
|
||||
args = append(args, "-T")
|
||||
if len(this.config.ServerAddr) > 0 {
|
||||
args = append(args, "-n", this.config.ServerAddr)
|
||||
}
|
||||
if this.config.ServerPort > 0 {
|
||||
args = append(args, "-P", strconv.Itoa(this.config.ServerPort))
|
||||
}
|
||||
case SyslogStorageProtocolUDP:
|
||||
args = append(args, "-d")
|
||||
if len(this.config.ServerAddr) > 0 {
|
||||
args = append(args, "-n", this.config.ServerAddr)
|
||||
}
|
||||
if this.config.ServerPort > 0 {
|
||||
args = append(args, "-P", strconv.Itoa(this.config.ServerPort))
|
||||
}
|
||||
case SyslogStorageProtocolSocket:
|
||||
args = append(args, "-u")
|
||||
args = append(args, this.config.Socket)
|
||||
case SyslogStorageProtocolNone:
|
||||
// do nothing
|
||||
}
|
||||
|
||||
args = append(args, "-S", "10240")
|
||||
|
||||
cmd := exec.Command(this.exe, args...)
|
||||
w, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, accessLog := range accessLogs {
|
||||
data, err := this.Marshal(accessLog)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
continue
|
||||
}
|
||||
_, err = w.Write(data)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
|
||||
_, err = w.Write([]byte("\n"))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
_ = w.Close()
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭
|
||||
func (this *SyslogStorage) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// TCPStorage TCP存储策略
|
||||
type TCPStorage struct {
|
||||
BaseStorage
|
||||
|
||||
config *serverconfigs.AccessLogTCPStorageConfig
|
||||
|
||||
writeLocker sync.Mutex
|
||||
|
||||
connLocker sync.Mutex
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func NewTCPStorage(config *serverconfigs.AccessLogTCPStorageConfig) *TCPStorage {
|
||||
return &TCPStorage{config: config}
|
||||
}
|
||||
|
||||
func (this *TCPStorage) Config() interface{} {
|
||||
return this.config
|
||||
}
|
||||
|
||||
// Start 开启
|
||||
func (this *TCPStorage) Start() error {
|
||||
if len(this.config.Network) == 0 {
|
||||
return errors.New("'network' should not be empty")
|
||||
}
|
||||
if len(this.config.Addr) == 0 {
|
||||
return errors.New("'addr' should not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 写入日志
|
||||
func (this *TCPStorage) Write(accessLogs []*pb.HTTPAccessLog) error {
|
||||
if len(accessLogs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := this.connect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
conn := this.conn
|
||||
if conn == nil {
|
||||
return errors.New("connection should not be nil")
|
||||
}
|
||||
|
||||
this.writeLocker.Lock()
|
||||
defer this.writeLocker.Unlock()
|
||||
|
||||
for _, accessLog := range accessLogs {
|
||||
data, err := this.Marshal(accessLog)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
continue
|
||||
}
|
||||
_, err = conn.Write(data)
|
||||
if err != nil {
|
||||
_ = this.Close()
|
||||
break
|
||||
}
|
||||
_, err = conn.Write([]byte("\n"))
|
||||
if err != nil {
|
||||
_ = this.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭
|
||||
func (this *TCPStorage) Close() error {
|
||||
this.connLocker.Lock()
|
||||
defer this.connLocker.Unlock()
|
||||
|
||||
if this.conn != nil {
|
||||
err := this.conn.Close()
|
||||
this.conn = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (this *TCPStorage) connect() error {
|
||||
this.connLocker.Lock()
|
||||
defer this.connLocker.Unlock()
|
||||
|
||||
if this.conn != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, err := net.Dial(this.config.Network, this.config.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
this.conn = conn
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package accesslogs
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTCPStorage_Write(t *testing.T) {
|
||||
go func() {
|
||||
server, err := net.Listen("tcp", "127.0.0.1:9981")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
for {
|
||||
conn, err := server.Accept()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
t.Log(string(buf[:n]))
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
_ = server.Close()
|
||||
}()
|
||||
|
||||
storage := NewTCPStorage(&serverconfigs.AccessLogTCPStorageConfig{
|
||||
Network: "tcp",
|
||||
Addr: "127.0.0.1:9981",
|
||||
})
|
||||
err := storage.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
{
|
||||
err = storage.Write([]*pb.HTTPAccessLog{
|
||||
{
|
||||
RequestMethod: "POST",
|
||||
RequestPath: "/1",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
},
|
||||
{
|
||||
RequestMethod: "GET",
|
||||
RequestPath: "/2",
|
||||
TimeLocal: time.Now().Format("2/Jan/2006:15:04:05 -0700"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
err = storage.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<?php
|
||||
|
||||
// test command storage
|
||||
|
||||
// open access log file
|
||||
$fp = fopen("/tmp/goedge-command-storage.log", "a+");
|
||||
|
||||
// read access logs from stdin
|
||||
$stdin = fopen("php://stdin", "r");
|
||||
while(true) {
|
||||
if (feof($stdin)) {
|
||||
break;
|
||||
}
|
||||
$line = fgets($stdin);
|
||||
|
||||
// write to access log file
|
||||
fwrite($fp, $line);
|
||||
}
|
||||
|
||||
// close file pointers
|
||||
fclose($fp);
|
||||
fclose($stdin);
|
||||
|
||||
?>
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/go-acme/lego/v4/challenge/dns01"
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
acmelog "github.com/go-acme/lego/v4/log"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
@@ -50,7 +50,7 @@ func (this *MyProvider) CleanUp(domain, token, keyAuth string) error {
|
||||
|
||||
// 参考 https://go-acme.github.io/lego/usage/library/
|
||||
func TestGenerate(t *testing.T) {
|
||||
acmelog.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
|
||||
acmelog.Logger = log.New(io.Discard, "", log.LstdFlags)
|
||||
|
||||
// 生成私钥
|
||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
@@ -94,7 +94,7 @@ func TestGenerate(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGenerate_EAB(t *testing.T) {
|
||||
acmelog.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
|
||||
acmelog.Logger = log.New(io.Discard, "", log.LstdFlags)
|
||||
|
||||
// 生成私钥
|
||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
@@ -130,6 +130,9 @@ func TestGenerate_EAB(t *testing.T) {
|
||||
} else {
|
||||
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
myUser.Registration = reg
|
||||
|
||||
request := certificate.ObtainRequest{
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/dnsclients"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/dnsclients/dnstypes"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/go-acme/lego/v4/challenge/dns01"
|
||||
"github.com/iwind/TeaGo/lists"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type DNSProvider struct {
|
||||
raw dnsclients.ProviderInterface
|
||||
dnsDomain string
|
||||
|
||||
locker sync.Mutex
|
||||
deletedRecordNames []string
|
||||
}
|
||||
|
||||
func NewDNSProvider(raw dnsclients.ProviderInterface, dnsDomain string) *DNSProvider {
|
||||
@@ -21,39 +28,47 @@ func NewDNSProvider(raw dnsclients.ProviderInterface, dnsDomain string) *DNSProv
|
||||
}
|
||||
|
||||
func (this *DNSProvider) Present(domain, token, keyAuth string) error {
|
||||
_ = os.Setenv("LEGO_DISABLE_CNAME_SUPPORT", "true")
|
||||
fqdn, value := dns01.GetRecord(domain, keyAuth)
|
||||
|
||||
// 设置记录
|
||||
index := strings.Index(fqdn, "."+this.dnsDomain)
|
||||
var index = strings.Index(fqdn, "."+this.dnsDomain)
|
||||
if index < 0 {
|
||||
return errors.New("invalid fqdn value")
|
||||
}
|
||||
recordName := fqdn[:index]
|
||||
record, err := this.raw.QueryRecord(this.dnsDomain, recordName, dnstypes.RecordTypeTXT)
|
||||
if err != nil {
|
||||
return errors.New("query DNS record failed: " + err.Error())
|
||||
var recordName = fqdn[:index]
|
||||
|
||||
// 先删除老的
|
||||
this.locker.Lock()
|
||||
var wasDeleted = lists.ContainsString(this.deletedRecordNames, recordName)
|
||||
this.locker.Unlock()
|
||||
|
||||
if !wasDeleted {
|
||||
records, err := this.raw.QueryRecords(this.dnsDomain, recordName, dnstypes.RecordTypeTXT)
|
||||
if err != nil {
|
||||
return fmt.Errorf("query DNS record failed: %w", err)
|
||||
}
|
||||
for _, record := range records {
|
||||
err = this.raw.DeleteRecord(this.dnsDomain, record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
this.locker.Lock()
|
||||
this.deletedRecordNames = append(this.deletedRecordNames, recordName)
|
||||
this.locker.Unlock()
|
||||
}
|
||||
if record == nil {
|
||||
err = this.raw.AddRecord(this.dnsDomain, &dnstypes.Record{
|
||||
Id: "",
|
||||
Name: recordName,
|
||||
Type: dnstypes.RecordTypeTXT,
|
||||
Value: value,
|
||||
Route: this.raw.DefaultRoute(),
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("create DNS record failed: " + err.Error())
|
||||
}
|
||||
} else {
|
||||
err = this.raw.UpdateRecord(this.dnsDomain, record, &dnstypes.Record{
|
||||
Name: recordName,
|
||||
Type: dnstypes.RecordTypeTXT,
|
||||
Value: value,
|
||||
Route: this.raw.DefaultRoute(),
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("update DNS record failed: " + err.Error())
|
||||
}
|
||||
|
||||
// 添加新的
|
||||
err := this.raw.AddRecord(this.dnsDomain, &dnstypes.Record{
|
||||
Id: "",
|
||||
Name: recordName,
|
||||
Type: dnstypes.RecordTypeTXT,
|
||||
Value: value,
|
||||
Route: this.raw.DefaultRoute(),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create DNS record failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -9,30 +9,11 @@ type Provider struct {
|
||||
Code string `json:"code"`
|
||||
Description string `json:"description"`
|
||||
APIURL string `json:"apiURL"`
|
||||
TestAPIURL string `json:"testAPIURL"`
|
||||
RequireEAB bool `json:"requireEAB"`
|
||||
EABDescription string `json:"eabDescription"`
|
||||
}
|
||||
|
||||
func FindAllProviders() []*Provider {
|
||||
return []*Provider{
|
||||
{
|
||||
Name: "Let's Encrypt",
|
||||
Code: DefaultProviderCode,
|
||||
Description: "非盈利组织Let's Encrypt提供的免费证书。",
|
||||
APIURL: "https://acme-v02.api.letsencrypt.org/directory",
|
||||
RequireEAB: false,
|
||||
},
|
||||
{
|
||||
Name: "ZeroSSL",
|
||||
Code: "zerossl",
|
||||
Description: "相关文档 <a href=\"https://zerossl.com/documentation/acme/\" target=\"_blank\">https://zerossl.com/documentation/acme/</a>。",
|
||||
APIURL: "https://acme.zerossl.com/v2/DV90",
|
||||
RequireEAB: true,
|
||||
EABDescription: "在官网<a href=\"https://app.zerossl.com/developer\" target=\"_blank\">[Developer]</a>页面底部点击\"Generate\"按钮生成。",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func FindProviderWithCode(code string) *Provider {
|
||||
for _, provider := range FindAllProviders() {
|
||||
if provider.Code == code {
|
||||
|
||||
24
internal/acme/providers_ext.go
Normal file
24
internal/acme/providers_ext.go
Normal file
@@ -0,0 +1,24 @@
|
||||
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||
//go:build !plus
|
||||
|
||||
package acme
|
||||
|
||||
func FindAllProviders() []*Provider {
|
||||
return []*Provider{
|
||||
{
|
||||
Name: "Let's Encrypt",
|
||||
Code: DefaultProviderCode,
|
||||
Description: "非盈利组织Let's Encrypt提供的免费证书。",
|
||||
APIURL: "https://acme-v02.api.letsencrypt.org/directory",
|
||||
RequireEAB: false,
|
||||
},
|
||||
{
|
||||
Name: "ZeroSSL",
|
||||
Code: "zerossl",
|
||||
Description: "相关文档 <a href=\"https://zerossl.com/documentation/acme/\" target=\"_blank\">https://zerossl.com/documentation/acme/</a>。",
|
||||
APIURL: "https://acme.zerossl.com/v2/DV90",
|
||||
RequireEAB: true,
|
||||
EABDescription: "在官网<a href=\"https://app.zerossl.com/developer\" target=\"_blank\">[Developer]</a>页面底部点击\"Generate\"按钮生成。",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/go-acme/lego/v4/certcrypto"
|
||||
@@ -8,7 +9,8 @@ import (
|
||||
"github.com/go-acme/lego/v4/lego"
|
||||
acmelog "github.com/go-acme/lego/v4/log"
|
||||
"github.com/go-acme/lego/v4/registration"
|
||||
"io/ioutil"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"io"
|
||||
"log"
|
||||
)
|
||||
|
||||
@@ -40,6 +42,7 @@ func (this *Request) Run() (certData []byte, keyData []byte, err error) {
|
||||
}
|
||||
if this.task.Provider.RequireEAB && this.task.Account == nil {
|
||||
err = errors.New("account should not be nil when provider require EAB")
|
||||
return
|
||||
}
|
||||
|
||||
switch this.task.AuthType {
|
||||
@@ -55,7 +58,9 @@ func (this *Request) Run() (certData []byte, keyData []byte, err error) {
|
||||
|
||||
func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
|
||||
if !this.debug {
|
||||
acmelog.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
|
||||
if !Tea.IsTesting() {
|
||||
acmelog.Logger = log.New(io.Discard, "", log.LstdFlags)
|
||||
}
|
||||
}
|
||||
|
||||
if this.task.User == nil {
|
||||
@@ -75,7 +80,7 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
config := lego.NewConfig(this.task.User)
|
||||
var config = lego.NewConfig(this.task.User)
|
||||
config.Certificate.KeyType = certcrypto.RSA2048
|
||||
config.CADirURL = this.task.Provider.APIURL
|
||||
config.UserAgent = teaconst.ProductName + "/" + teaconst.Version
|
||||
@@ -86,28 +91,28 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
|
||||
}
|
||||
|
||||
// 注册用户
|
||||
resource := this.task.User.GetRegistration()
|
||||
var resource = this.task.User.GetRegistration()
|
||||
if resource != nil {
|
||||
resource, err = client.Registration.QueryRegistration()
|
||||
_, err = client.Registration.QueryRegistration()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
if this.task.Provider.RequireEAB {
|
||||
resource, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
resource, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
TermsOfServiceAgreed: true,
|
||||
Kid: this.task.Account.EABKid,
|
||||
HmacEncoded: this.task.Account.EABKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("register user failed: " + err.Error())
|
||||
return nil, nil, fmt.Errorf("register user failed: %w", err)
|
||||
}
|
||||
err = this.task.User.Register(resource)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
resource, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
resource, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -124,13 +129,13 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
|
||||
}
|
||||
|
||||
// 申请证书
|
||||
request := certificate.ObtainRequest{
|
||||
var request = certificate.ObtainRequest{
|
||||
Domains: this.task.Domains,
|
||||
Bundle: true,
|
||||
}
|
||||
certResource, err := client.Certificate.Obtain(request)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("obtain cert failed: " + err.Error())
|
||||
return nil, nil, fmt.Errorf("obtain cert failed: %w", err)
|
||||
}
|
||||
|
||||
return certResource.Certificate, certResource.PrivateKey, nil
|
||||
@@ -138,7 +143,9 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
|
||||
|
||||
func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
|
||||
if !this.debug {
|
||||
acmelog.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
|
||||
if !Tea.IsTesting() {
|
||||
acmelog.Logger = log.New(io.Discard, "", log.LstdFlags)
|
||||
}
|
||||
}
|
||||
|
||||
if this.task.User == nil {
|
||||
@@ -146,7 +153,7 @@ func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
config := lego.NewConfig(this.task.User)
|
||||
var config = lego.NewConfig(this.task.User)
|
||||
config.Certificate.KeyType = certcrypto.RSA2048
|
||||
config.CADirURL = this.task.Provider.APIURL
|
||||
config.UserAgent = teaconst.ProductName + "/" + teaconst.Version
|
||||
@@ -157,28 +164,28 @@ func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
|
||||
}
|
||||
|
||||
// 注册用户
|
||||
resource := this.task.User.GetRegistration()
|
||||
var resource = this.task.User.GetRegistration()
|
||||
if resource != nil {
|
||||
resource, err = client.Registration.QueryRegistration()
|
||||
_, err = client.Registration.QueryRegistration()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
if this.task.Provider.RequireEAB {
|
||||
resource, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
resource, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
|
||||
TermsOfServiceAgreed: true,
|
||||
Kid: this.task.Account.EABKid,
|
||||
HmacEncoded: this.task.Account.EABKey,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("register user failed: " + err.Error())
|
||||
return nil, nil, fmt.Errorf("register user failed: %w", err)
|
||||
}
|
||||
err = this.task.User.Register(resource)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
resource, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
resource, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -195,7 +202,7 @@ func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
|
||||
}
|
||||
|
||||
// 申请证书
|
||||
request := certificate.ObtainRequest{
|
||||
var request = certificate.ObtainRequest{
|
||||
Domains: this.task.Domains,
|
||||
Bundle: true,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package apps
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
@@ -9,8 +10,10 @@ import (
|
||||
"github.com/iwind/gosock/pkg/gosock"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -184,13 +187,16 @@ func (this *AppCmd) runStart() {
|
||||
return
|
||||
}
|
||||
|
||||
cmd := exec.Command(os.Args[0])
|
||||
var cmd = exec.Command(this.exe())
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
fmt.Println(this.product+" start failed:", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// create symbolic links
|
||||
_ = this.createSymLinks()
|
||||
|
||||
fmt.Println(this.product+" started ok, pid:", cmd.Process.Pid)
|
||||
}
|
||||
|
||||
@@ -237,3 +243,58 @@ func (this *AppCmd) getPID() int {
|
||||
}
|
||||
return maps.NewMap(reply.Params).GetInt("pid")
|
||||
}
|
||||
|
||||
func (this *AppCmd) exe() string {
|
||||
var exe, _ = os.Executable()
|
||||
if len(exe) == 0 {
|
||||
exe = os.Args[0]
|
||||
}
|
||||
return exe
|
||||
}
|
||||
|
||||
// 创建软链接
|
||||
func (this *AppCmd) createSymLinks() error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var exe, _ = os.Executable()
|
||||
if len(exe) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errorList = []string{}
|
||||
|
||||
// bin
|
||||
{
|
||||
var target = "/usr/bin/" + teaconst.ProcessName
|
||||
old, _ := filepath.EvalSymlinks(target)
|
||||
if old != exe {
|
||||
_ = os.Remove(target)
|
||||
err := os.Symlink(exe, target)
|
||||
if err != nil {
|
||||
errorList = append(errorList, err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log
|
||||
{
|
||||
var realPath = filepath.Dir(filepath.Dir(exe)) + "/logs/run.log"
|
||||
var target = "/var/log/" + teaconst.ProcessName + ".log"
|
||||
old, _ := filepath.EvalSymlinks(target)
|
||||
if old != realPath {
|
||||
_ = os.Remove(target)
|
||||
err := os.Symlink(realPath, target)
|
||||
if err != nil {
|
||||
errorList = append(errorList, err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(errorList) > 0 {
|
||||
return errors.New(strings.Join(errorList, "\n"))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,51 +1,108 @@
|
||||
package apps
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/goman"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils/sizes"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/files"
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
"github.com/iwind/TeaGo/utils/time"
|
||||
timeutil "github.com/iwind/TeaGo/utils/time"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type LogWriter struct {
|
||||
fileAppender *files.Appender
|
||||
fp *os.File
|
||||
c chan string
|
||||
}
|
||||
|
||||
func (this *LogWriter) Init() {
|
||||
// 创建目录
|
||||
dir := files.NewFile(Tea.LogDir())
|
||||
var dir = files.NewFile(Tea.LogDir())
|
||||
if !dir.Exists() {
|
||||
err := dir.Mkdir()
|
||||
if err != nil {
|
||||
log.Println("[error]" + err.Error())
|
||||
log.Println("[LOG]create log dir failed: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
logFile := files.NewFile(Tea.LogFile("run.log"))
|
||||
|
||||
// 打开要写入的日志文件
|
||||
appender, err := logFile.Appender()
|
||||
var logPath = Tea.LogFile("run.log")
|
||||
fp, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
log.Println("[LOG]open log file failed: " + err.Error())
|
||||
} else {
|
||||
this.fileAppender = appender
|
||||
this.fp = fp
|
||||
}
|
||||
|
||||
this.c = make(chan string, 1024)
|
||||
|
||||
// 异步写入文件
|
||||
var maxFileSize = 2 * sizes.G // 文件最大尺寸,超出此尺寸则清空
|
||||
if fp != nil {
|
||||
goman.New(func() {
|
||||
var totalSize int64 = 0
|
||||
stat, err := fp.Stat()
|
||||
if err == nil {
|
||||
totalSize = stat.Size()
|
||||
}
|
||||
|
||||
for message := range this.c {
|
||||
totalSize += int64(len(message))
|
||||
_, err := fp.WriteString(timeutil.Format("Y/m/d H:i:s ") + message + "\n")
|
||||
if err != nil {
|
||||
log.Println("[LOG]write log failed: " + err.Error())
|
||||
} else {
|
||||
// 如果太大则Truncate
|
||||
if totalSize > maxFileSize {
|
||||
_ = fp.Truncate(0)
|
||||
totalSize = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LogWriter) Write(message string) {
|
||||
log.Println(message)
|
||||
backgroundEnv, _ := os.LookupEnv("EdgeBackground")
|
||||
if backgroundEnv != "on" {
|
||||
// 文件和行号
|
||||
var file string
|
||||
var line int
|
||||
if Tea.IsTesting() {
|
||||
var callDepth = 3
|
||||
var ok bool
|
||||
_, file, line, ok = runtime.Caller(callDepth)
|
||||
if ok {
|
||||
file = this.packagePath(file)
|
||||
}
|
||||
}
|
||||
|
||||
if this.fileAppender != nil {
|
||||
_, err := this.fileAppender.AppendString(timeutil.Format("Y/m/d H:i:s ") + message + "\n")
|
||||
if err != nil {
|
||||
log.Println("[error]" + err.Error())
|
||||
if len(file) > 0 {
|
||||
log.Println(message + " (" + file + ":" + strconv.Itoa(line) + ")")
|
||||
} else {
|
||||
log.Println(message)
|
||||
}
|
||||
}
|
||||
|
||||
this.c <- message
|
||||
}
|
||||
|
||||
func (this *LogWriter) Close() {
|
||||
if this.fileAppender != nil {
|
||||
_ = this.fileAppender.Close()
|
||||
if this.fp != nil {
|
||||
_ = this.fp.Close()
|
||||
}
|
||||
|
||||
close(this.c)
|
||||
}
|
||||
|
||||
func (this *LogWriter) packagePath(path string) string {
|
||||
var pieces = strings.Split(path, "/")
|
||||
if len(pieces) >= 2 {
|
||||
return strings.Join(pieces[len(pieces)-2:], "/")
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"gopkg.in/yaml.v3"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
@@ -42,7 +41,7 @@ func SharedAPIConfig() (*APIConfig, error) {
|
||||
var data []byte
|
||||
var err error
|
||||
for _, path := range paths {
|
||||
data, err = ioutil.ReadFile(path)
|
||||
data, err = os.ReadFile(path)
|
||||
if err == nil {
|
||||
if path == localFile {
|
||||
isFromLocal = true
|
||||
@@ -63,7 +62,7 @@ func SharedAPIConfig() (*APIConfig, error) {
|
||||
|
||||
if !isFromLocal {
|
||||
// 恢复文件
|
||||
_ = ioutil.WriteFile(localFile, data, 0666)
|
||||
_ = os.WriteFile(localFile, data, 0666)
|
||||
}
|
||||
|
||||
// 恢复数据库文件
|
||||
@@ -80,9 +79,9 @@ func SharedAPIConfig() (*APIConfig, error) {
|
||||
for _, path := range paths {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
data, err := ioutil.ReadFile(path)
|
||||
data, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
_ = ioutil.WriteFile(dbConfigFile, data, 0666)
|
||||
_ = os.WriteFile(dbConfigFile, data, 0666)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -122,14 +121,58 @@ func (this *APIConfig) WriteFile(path string) error {
|
||||
for _, backupDir := range backupDirs {
|
||||
stat, err := os.Stat(backupDir)
|
||||
if err == nil && stat.IsDir() {
|
||||
_ = ioutil.WriteFile(backupDir+"/"+filename, data, 0666)
|
||||
_ = os.WriteFile(backupDir+"/"+filename, data, 0666)
|
||||
} else if err != nil && os.IsNotExist(err) {
|
||||
err = os.Mkdir(backupDir, 0777)
|
||||
if err == nil {
|
||||
_ = ioutil.WriteFile(backupDir+"/"+filename, data, 0666)
|
||||
_ = os.WriteFile(backupDir+"/"+filename, data, 0666)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ioutil.WriteFile(path, data, 0666)
|
||||
return os.WriteFile(path, data, 0666)
|
||||
}
|
||||
|
||||
// ResetAPIConfig 重置配置
|
||||
func ResetAPIConfig() error {
|
||||
for _, filename := range []string{"api.yaml", "db.yaml"} {
|
||||
// 重置 configs/api.yaml
|
||||
{
|
||||
var configFile = Tea.ConfigFile(filename)
|
||||
stat, err := os.Stat(configFile)
|
||||
if err == nil && !stat.IsDir() {
|
||||
err = os.Remove(configFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置 ~/.edge-api/api.yaml
|
||||
homeDir, homeErr := os.UserHomeDir()
|
||||
if homeErr == nil {
|
||||
var configFile = homeDir + "/." + teaconst.ProcessName + "/" + filename
|
||||
stat, err := os.Stat(configFile)
|
||||
if err == nil && !stat.IsDir() {
|
||||
err = os.Remove(configFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置 /etc/edge-api/api.yaml
|
||||
{
|
||||
var configFile = "/etc/" + teaconst.ProcessName + "/" + filename
|
||||
stat, err := os.Stat(configFile)
|
||||
if err == nil && !stat.IsDir() {
|
||||
err = os.Remove(configFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package teaconst
|
||||
|
||||
const (
|
||||
Version = "0.4.5"
|
||||
Version = "1.3.8"
|
||||
|
||||
ProductName = "Edge API"
|
||||
ProcessName = "edge-api"
|
||||
ProductNameZH = "Edge"
|
||||
|
||||
GlobalProductName = "GoEdge"
|
||||
|
||||
Role = "api"
|
||||
|
||||
EncryptKey = "8f983f4d69b83aaa0d74b21a212f6967"
|
||||
@@ -18,13 +20,5 @@ const (
|
||||
|
||||
// 其他节点版本号,用来检测是否有需要升级的节点
|
||||
|
||||
NodeVersion = "0.4.5"
|
||||
UserNodeVersion = "0.3.2"
|
||||
AuthorityNodeVersion = "0.0.2"
|
||||
MonitorNodeVersion = "0.0.3"
|
||||
DNSNodeVersion = "0.2.1"
|
||||
ReportNodeVersion = "0.1.0"
|
||||
|
||||
// SQLVersion SQL版本号
|
||||
SQLVersion = "5"
|
||||
NodeVersion = "1.3.8"
|
||||
)
|
||||
|
||||
9
internal/const/const_community.go
Normal file
9
internal/const/const_community.go
Normal file
@@ -0,0 +1,9 @@
|
||||
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||
//go:build !plus
|
||||
|
||||
package teaconst
|
||||
|
||||
const (
|
||||
// DefaultMaxNodes 节点数限制
|
||||
DefaultMaxNodes int32 = 50
|
||||
)
|
||||
@@ -2,9 +2,34 @@
|
||||
|
||||
package teaconst
|
||||
|
||||
var (
|
||||
IsPlus = false
|
||||
MaxNodes int32 = 0
|
||||
NodeId int64 = 0
|
||||
Debug = false
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"github.com/iwind/TeaGo/rands"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
IsPlus = false
|
||||
Edition = ""
|
||||
MaxNodes int32 = 0
|
||||
NodeId int64 = 0
|
||||
Debug = false
|
||||
InstanceCode = fmt.Sprintf("%x", sha1.Sum([]byte("INSTANCE"+types.String(time.Now().UnixNano())+"@"+types.String(rands.Int64()))))
|
||||
IsMain = checkMain()
|
||||
)
|
||||
|
||||
// 检查是否为主程序
|
||||
func checkMain() bool {
|
||||
if len(os.Args) == 1 ||
|
||||
(len(os.Args) >= 2 && os.Args[1] == "pprof") {
|
||||
return true
|
||||
}
|
||||
exe, _ := os.Executable()
|
||||
return strings.HasSuffix(exe, ".test") ||
|
||||
strings.HasSuffix(exe, ".test.exe") ||
|
||||
strings.Contains(exe, "___")
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
@@ -42,3 +43,13 @@ func TestDB_Instance(t *testing.T) {
|
||||
}
|
||||
time.Sleep(100 * time.Second)
|
||||
}
|
||||
|
||||
func TestDB_Reuse(t *testing.T) {
|
||||
var dao = models.NewVersionDAO()
|
||||
for i := 0; i < 20_000; i++ {
|
||||
_, _, err := dao.Query(nil).Attr("version", i).Reuse(true).FindOne()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
33
internal/db/models/accounts/order_method_dao.go
Normal file
33
internal/db/models/accounts/order_method_dao.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
OrderMethodStateEnabled = 1 // 已启用
|
||||
OrderMethodStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type OrderMethodDAO dbs.DAO
|
||||
|
||||
func NewOrderMethodDAO() *OrderMethodDAO {
|
||||
return dbs.NewDAO(&OrderMethodDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeOrderMethods",
|
||||
Model: new(OrderMethod),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*OrderMethodDAO)
|
||||
}
|
||||
|
||||
var SharedOrderMethodDAO *OrderMethodDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedOrderMethodDAO = NewOrderMethodDAO()
|
||||
})
|
||||
}
|
||||
6
internal/db/models/accounts/order_method_dao_test.go
Normal file
6
internal/db/models/accounts/order_method_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package accounts_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
40
internal/db/models/accounts/order_method_model.go
Normal file
40
internal/db/models/accounts/order_method_model.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package accounts
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// OrderMethod 订单支付方式
|
||||
type OrderMethod struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
Name string `field:"name"` // 名称
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
Description string `field:"description"` // 描述
|
||||
ParentCode string `field:"parentCode"` // 内置的父级代号
|
||||
Code string `field:"code"` // 代号
|
||||
Url string `field:"url"` // URL
|
||||
Secret string `field:"secret"` // 密钥
|
||||
Params dbs.JSON `field:"params"` // 参数
|
||||
ClientType string `field:"clientType"` // 客户端类型
|
||||
QrcodeTitle string `field:"qrcodeTitle"` // 二维码标题
|
||||
Order uint32 `field:"order"` // 排序
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type OrderMethodOperator struct {
|
||||
Id any // ID
|
||||
Name any // 名称
|
||||
IsOn any // 是否启用
|
||||
Description any // 描述
|
||||
ParentCode any // 内置的父级代号
|
||||
Code any // 代号
|
||||
Url any // URL
|
||||
Secret any // 密钥
|
||||
Params any // 参数
|
||||
ClientType any // 客户端类型
|
||||
QrcodeTitle any // 二维码标题
|
||||
Order any // 排序
|
||||
State any // 状态
|
||||
}
|
||||
|
||||
func NewOrderMethodOperator() *OrderMethodOperator {
|
||||
return &OrderMethodOperator{}
|
||||
}
|
||||
1
internal/db/models/accounts/order_method_model_ext.go
Normal file
1
internal/db/models/accounts/order_method_model_ext.go
Normal file
@@ -0,0 +1 @@
|
||||
package accounts
|
||||
@@ -1,80 +0,0 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/userconfigs"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"github.com/iwind/TeaGo/maps"
|
||||
timeutil "github.com/iwind/TeaGo/utils/time"
|
||||
)
|
||||
|
||||
type UserAccountDailyStatDAO dbs.DAO
|
||||
|
||||
func NewUserAccountDailyStatDAO() *UserAccountDailyStatDAO {
|
||||
return dbs.NewDAO(&UserAccountDailyStatDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeUserAccountDailyStats",
|
||||
Model: new(UserAccountDailyStat),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*UserAccountDailyStatDAO)
|
||||
}
|
||||
|
||||
var SharedUserAccountDailyStatDAO *UserAccountDailyStatDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedUserAccountDailyStatDAO = NewUserAccountDailyStatDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateDailyStat 更新当天统计数据
|
||||
func (this *UserAccountDailyStatDAO) UpdateDailyStat(tx *dbs.Tx) error {
|
||||
var day = timeutil.Format("Ymd")
|
||||
var month = timeutil.Format("Ym")
|
||||
income, err := SharedUserAccountLogDAO.SumDailyEventTypes(tx, day, userconfigs.AccountIncomeEventTypes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
expense, err := SharedUserAccountLogDAO.SumDailyEventTypes(tx, day, userconfigs.AccountExpenseEventTypes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if expense < 0 {
|
||||
expense = -expense
|
||||
}
|
||||
|
||||
return this.Query(tx).
|
||||
InsertOrUpdateQuickly(maps.Map{
|
||||
"day": day,
|
||||
"month": month,
|
||||
"income": income,
|
||||
"expense": expense,
|
||||
}, maps.Map{
|
||||
"income": income,
|
||||
"expense": expense,
|
||||
})
|
||||
}
|
||||
|
||||
// FindDailyStats 查看按天统计
|
||||
func (this *UserAccountDailyStatDAO) FindDailyStats(tx *dbs.Tx, dayFrom string, dayTo string) (result []*UserAccountDailyStat, err error) {
|
||||
_, err = this.Query(tx).
|
||||
Between("day", dayFrom, dayTo).
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
|
||||
// FindMonthlyStats 查看某月统计
|
||||
func (this *UserAccountDailyStatDAO) FindMonthlyStats(tx *dbs.Tx, dayFrom string, dayTo string) (result []*UserAccountDailyStat, err error) {
|
||||
_, err = this.Query(tx).
|
||||
Result("SUM(income) AS income", "SUM(expense) AS expense", "month").
|
||||
Between("day", dayFrom, dayTo).
|
||||
Group("month").
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/goman"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/userconfigs"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"github.com/iwind/TeaGo/lists"
|
||||
"github.com/iwind/TeaGo/maps"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
dbs.OnReadyDone(func() {
|
||||
goman.New(func() {
|
||||
// 自动支付账单任务
|
||||
var ticker = time.NewTicker(12 * time.Hour)
|
||||
for range ticker.C {
|
||||
if SharedUserAccountDAO.Instance != nil {
|
||||
err := SharedUserAccountDAO.Instance.RunTx(func(tx *dbs.Tx) error {
|
||||
return SharedUserAccountDAO.PayBills(tx)
|
||||
})
|
||||
if err != nil {
|
||||
remotelogs.Error("USER_ACCOUNT_DAO", "pay bills task failed: "+err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type UserAccountDAO dbs.DAO
|
||||
|
||||
func NewUserAccountDAO() *UserAccountDAO {
|
||||
return dbs.NewDAO(&UserAccountDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeUserAccounts",
|
||||
Model: new(UserAccount),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*UserAccountDAO)
|
||||
}
|
||||
|
||||
var SharedUserAccountDAO *UserAccountDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedUserAccountDAO = NewUserAccountDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// FindUserAccountWithUserId 根据用户ID查找用户账户
|
||||
func (this *UserAccountDAO) FindUserAccountWithUserId(tx *dbs.Tx, userId int64) (*UserAccount, error) {
|
||||
if userId <= 0 {
|
||||
return nil, errors.New("invalid userId '" + types.String(userId) + "'")
|
||||
}
|
||||
|
||||
// 用户是否存在
|
||||
user, err := models.SharedUserDAO.FindEnabledUser(tx, userId, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user == nil {
|
||||
return nil, errors.New("invalid userId '" + types.String(userId) + "'")
|
||||
}
|
||||
|
||||
account, err := this.Query(tx).
|
||||
Attr("userId", userId).
|
||||
Find()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if account != nil {
|
||||
return account.(*UserAccount), nil
|
||||
}
|
||||
|
||||
var op = NewUserAccountOperator()
|
||||
op.UserId = userId
|
||||
_, err = this.SaveInt64(tx, op)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return this.FindUserAccountWithUserId(tx, userId)
|
||||
}
|
||||
|
||||
// FindUserAccountWithAccountId 根据ID查找用户账户
|
||||
func (this *UserAccountDAO) FindUserAccountWithAccountId(tx *dbs.Tx, accountId int64) (*UserAccount, error) {
|
||||
one, err := this.Query(tx).
|
||||
Pk(accountId).
|
||||
Find()
|
||||
if one != nil {
|
||||
return one.(*UserAccount), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// UpdateUserAccount 操作用户账户
|
||||
func (this *UserAccountDAO) UpdateUserAccount(tx *dbs.Tx, accountId int64, delta float32, eventType userconfigs.AccountEventType, description string, params maps.Map) error {
|
||||
account, err := this.FindUserAccountWithAccountId(tx, accountId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if account == nil {
|
||||
return errors.New("invalid account id '" + types.String(accountId) + "'")
|
||||
}
|
||||
var userId = int64(account.UserId)
|
||||
var deltaFloat64 = float64(delta)
|
||||
if deltaFloat64 < 0 && account.Total < -deltaFloat64 {
|
||||
return errors.New("not enough account quota to decrease")
|
||||
}
|
||||
|
||||
// 操作账户
|
||||
err = this.Query(tx).
|
||||
Pk(account.Id).
|
||||
Set("total", dbs.SQL("total+:delta")).
|
||||
Param("delta", delta).
|
||||
UpdateQuickly()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 生成日志
|
||||
err = SharedUserAccountLogDAO.CreateAccountLog(tx, userId, accountId, delta, 0, eventType, description, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateUserAccountFrozen 操作用户账户冻结余额
|
||||
func (this *UserAccountDAO) UpdateUserAccountFrozen(tx *dbs.Tx, userId int64, delta float32, eventType userconfigs.AccountEventType, description string, params maps.Map) error {
|
||||
account, err := this.FindUserAccountWithUserId(tx, userId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var deltaFloat64 = float64(delta)
|
||||
if deltaFloat64 < 0 && account.TotalFrozen < -deltaFloat64 {
|
||||
return errors.New("not enough account frozen quota to decrease")
|
||||
}
|
||||
|
||||
// 操作账户
|
||||
err = this.Query(tx).
|
||||
Pk(account.Id).
|
||||
Set("totalFrozen", dbs.SQL("total+:delta")).
|
||||
Param("delta", delta).
|
||||
UpdateQuickly()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 生成日志
|
||||
err = SharedUserAccountLogDAO.CreateAccountLog(tx, userId, int64(account.Id), 0, delta, eventType, description, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountAllAccounts 计算所有账户数量
|
||||
func (this *UserAccountDAO) CountAllAccounts(tx *dbs.Tx, keyword string) (int64, error) {
|
||||
var query = this.Query(tx)
|
||||
if len(keyword) > 0 {
|
||||
query.Where("userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1 AND (username LIKE :keyword OR fullname LIKE :keyword))")
|
||||
query.Param("keyword", keyword)
|
||||
} else {
|
||||
query.Where("userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1)")
|
||||
}
|
||||
return query.Count()
|
||||
}
|
||||
|
||||
// ListAccounts 列出单页账户
|
||||
func (this *UserAccountDAO) ListAccounts(tx *dbs.Tx, keyword string, offset int64, size int64) (result []*UserAccount, err error) {
|
||||
var query = this.Query(tx)
|
||||
if len(keyword) > 0 {
|
||||
query.Where("userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1 AND (username LIKE :keyword OR fullname LIKE :keyword))")
|
||||
query.Param("keyword", keyword)
|
||||
} else {
|
||||
query.Where("userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1)")
|
||||
}
|
||||
_, err = query.
|
||||
DescPk().
|
||||
Offset(offset).
|
||||
Limit(size).
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
|
||||
// PayBills 尝试自动支付账单
|
||||
func (this *UserAccountDAO) PayBills(tx *dbs.Tx) error {
|
||||
bills, err := models.SharedUserBillDAO.FindUnpaidBills(tx, 10000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 先支付久远的
|
||||
lists.Reverse(bills)
|
||||
|
||||
for _, bill := range bills {
|
||||
if bill.Amount <= 0 {
|
||||
err = models.SharedUserBillDAO.UpdateUserBillIsPaid(tx, int64(bill.Id), true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
account, err := SharedUserAccountDAO.FindUserAccountWithUserId(tx, int64(bill.UserId))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if account == nil || account.Total < bill.Amount {
|
||||
continue
|
||||
}
|
||||
|
||||
// 扣款
|
||||
err = SharedUserAccountDAO.UpdateUserAccount(tx, int64(account.Id), -float32(bill.Amount), userconfigs.AccountEventTypePayBill, "支付账单"+bill.Code, maps.Map{"billId": bill.Id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 改为已支付
|
||||
err = models.SharedUserBillDAO.UpdateUserBillIsPaid(tx, int64(bill.Id), true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckUserAccount 检查用户账户
|
||||
func (this *UserAccountDAO) CheckUserAccount(tx *dbs.Tx, userId int64, accountId int64) error {
|
||||
exists, err := this.Query(tx).
|
||||
Pk(accountId).
|
||||
Attr("userId", userId).
|
||||
Exist()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/userconfigs"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
"github.com/iwind/TeaGo/maps"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
timeutil "github.com/iwind/TeaGo/utils/time"
|
||||
)
|
||||
|
||||
type UserAccountLogDAO dbs.DAO
|
||||
|
||||
func NewUserAccountLogDAO() *UserAccountLogDAO {
|
||||
return dbs.NewDAO(&UserAccountLogDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeUserAccountLogs",
|
||||
Model: new(UserAccountLog),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*UserAccountLogDAO)
|
||||
}
|
||||
|
||||
var SharedUserAccountLogDAO *UserAccountLogDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedUserAccountLogDAO = NewUserAccountLogDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// CreateAccountLog 生成用户账户日志
|
||||
func (this *UserAccountLogDAO) CreateAccountLog(tx *dbs.Tx, userId int64, accountId int64, delta float32, deltaFrozen float32, eventType userconfigs.AccountEventType, description string, params maps.Map) error {
|
||||
var op = NewUserAccountLogOperator()
|
||||
op.UserId = userId
|
||||
op.AccountId = accountId
|
||||
op.Delta = delta
|
||||
op.DeltaFrozen = deltaFrozen
|
||||
|
||||
account, err := SharedUserAccountDAO.FindUserAccountWithAccountId(tx, accountId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if account == nil {
|
||||
return errors.New("invalid account id '" + types.String(accountId) + "'")
|
||||
}
|
||||
op.Total = account.Total
|
||||
op.TotalFrozen = account.TotalFrozen
|
||||
|
||||
op.EventType = eventType
|
||||
op.Description = description
|
||||
|
||||
if params == nil {
|
||||
params = maps.Map{}
|
||||
}
|
||||
op.Params = params.AsJSON()
|
||||
|
||||
op.Day = timeutil.Format("Ymd")
|
||||
err = this.Save(tx, op)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return SharedUserAccountDailyStatDAO.UpdateDailyStat(tx)
|
||||
}
|
||||
|
||||
// CountAccountLogs 计算日志数量
|
||||
func (this *UserAccountLogDAO) CountAccountLogs(tx *dbs.Tx, userId int64, accountId int64, keyword string, eventType string) (int64, error) {
|
||||
var query = this.Query(tx)
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
}
|
||||
if accountId > 0 {
|
||||
query.Attr("accountId", accountId)
|
||||
}
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1 AND (username LIKE :keyword OR fullname LIKE :keyword)) OR description LIKE :keyword)")
|
||||
query.Param("keyword", "%"+keyword+"%")
|
||||
}
|
||||
if len(eventType) > 0 {
|
||||
query.Attr("eventType", eventType)
|
||||
}
|
||||
return query.Count()
|
||||
}
|
||||
|
||||
// ListAccountLogs 列出单页日志
|
||||
func (this *UserAccountLogDAO) ListAccountLogs(tx *dbs.Tx, userId int64, accountId int64, keyword string, eventType string, offset int64, size int64) (result []*UserAccountLog, err error) {
|
||||
var query = this.Query(tx)
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
}
|
||||
if accountId > 0 {
|
||||
query.Attr("accountId", accountId)
|
||||
}
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(userId IN (SELECT id FROM " + models.SharedUserDAO.Table + " WHERE state=1 AND (username LIKE :keyword OR fullname LIKE :keyword)) OR description LIKE :keyword)")
|
||||
query.Param("keyword", "%"+keyword+"%")
|
||||
}
|
||||
if len(eventType) > 0 {
|
||||
query.Attr("eventType", eventType)
|
||||
}
|
||||
_, err = query.
|
||||
DescPk().
|
||||
Offset(offset).
|
||||
Limit(size).
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
|
||||
// SumDailyEventTypes 统计某天数据总和
|
||||
func (this *UserAccountLogDAO) SumDailyEventTypes(tx *dbs.Tx, day string, eventTypes []userconfigs.AccountEventType) (float32, error) {
|
||||
if len(eventTypes) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
result, err := this.Query(tx).
|
||||
Attr("day", day).
|
||||
Attr("eventType", eventTypes).
|
||||
Sum("delta", 0)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return types.Float32(result), nil
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
package accounts
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// UserAccountLog 用户账户日志
|
||||
type UserAccountLog struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
AccountId uint64 `field:"accountId"` // 账户ID
|
||||
Delta float64 `field:"delta"` // 操作余额的数量(可为负)
|
||||
DeltaFrozen float64 `field:"deltaFrozen"` // 操作冻结的数量(可为负)
|
||||
Total float64 `field:"total"` // 操作后余额
|
||||
TotalFrozen float64 `field:"totalFrozen"` // 操作后冻结余额
|
||||
EventType string `field:"eventType"` // 类型
|
||||
Description string `field:"description"` // 描述文字
|
||||
Day string `field:"day"` // YYYYMMDD
|
||||
CreatedAt uint64 `field:"createdAt"` // 时间
|
||||
Params string `field:"params"` // 参数
|
||||
Id uint64 `field:"id"` // ID
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
AccountId uint64 `field:"accountId"` // 账户ID
|
||||
Delta float64 `field:"delta"` // 操作余额的数量(可为负)
|
||||
DeltaFrozen float64 `field:"deltaFrozen"` // 操作冻结的数量(可为负)
|
||||
Total float64 `field:"total"` // 操作后余额
|
||||
TotalFrozen float64 `field:"totalFrozen"` // 操作后冻结余额
|
||||
EventType string `field:"eventType"` // 类型
|
||||
Description string `field:"description"` // 描述文字
|
||||
Day string `field:"day"` // YYYYMMDD
|
||||
CreatedAt uint64 `field:"createdAt"` // 时间
|
||||
Params dbs.JSON `field:"params"` // 参数
|
||||
}
|
||||
|
||||
type UserAccountLogOperator struct {
|
||||
|
||||
33
internal/db/models/accounts/user_order_dao.go
Normal file
33
internal/db/models/accounts/user_order_dao.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
UserOrderStateEnabled = 1 // 已启用
|
||||
UserOrderStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type UserOrderDAO dbs.DAO
|
||||
|
||||
func NewUserOrderDAO() *UserOrderDAO {
|
||||
return dbs.NewDAO(&UserOrderDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeUserOrders",
|
||||
Model: new(UserOrder),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*UserOrderDAO)
|
||||
}
|
||||
|
||||
var SharedUserOrderDAO *UserOrderDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedUserOrderDAO = NewUserOrderDAO()
|
||||
})
|
||||
}
|
||||
6
internal/db/models/accounts/user_order_dao_test.go
Normal file
6
internal/db/models/accounts/user_order_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package accounts_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
28
internal/db/models/accounts/user_order_log_dao.go
Normal file
28
internal/db/models/accounts/user_order_log_dao.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package accounts
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
type UserOrderLogDAO dbs.DAO
|
||||
|
||||
func NewUserOrderLogDAO() *UserOrderLogDAO {
|
||||
return dbs.NewDAO(&UserOrderLogDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeUserOrderLogs",
|
||||
Model: new(UserOrderLog),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*UserOrderLogDAO)
|
||||
}
|
||||
|
||||
var SharedUserOrderLogDAO *UserOrderLogDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedUserOrderLogDAO = NewUserOrderLogDAO()
|
||||
})
|
||||
}
|
||||
6
internal/db/models/accounts/user_order_log_dao_test.go
Normal file
6
internal/db/models/accounts/user_order_log_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package accounts_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
28
internal/db/models/accounts/user_order_log_model.go
Normal file
28
internal/db/models/accounts/user_order_log_model.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package accounts
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// UserOrderLog 订单日志
|
||||
type UserOrderLog struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
AdminId uint64 `field:"adminId"` // 管理员ID
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
OrderId uint64 `field:"orderId"` // 订单ID
|
||||
Status string `field:"status"` // 状态
|
||||
Snapshot dbs.JSON `field:"snapshot"` // 状态快照
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
}
|
||||
|
||||
type UserOrderLogOperator struct {
|
||||
Id interface{} // ID
|
||||
AdminId interface{} // 管理员ID
|
||||
UserId interface{} // 用户ID
|
||||
OrderId interface{} // 订单ID
|
||||
Status interface{} // 状态
|
||||
Snapshot interface{} // 状态快照
|
||||
CreatedAt interface{} // 创建时间
|
||||
}
|
||||
|
||||
func NewUserOrderLogOperator() *UserOrderLogOperator {
|
||||
return &UserOrderLogOperator{}
|
||||
}
|
||||
1
internal/db/models/accounts/user_order_log_model_ext.go
Normal file
1
internal/db/models/accounts/user_order_log_model_ext.go
Normal file
@@ -0,0 +1 @@
|
||||
package accounts
|
||||
40
internal/db/models/accounts/user_order_model.go
Normal file
40
internal/db/models/accounts/user_order_model.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package accounts
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// UserOrder 用户订单
|
||||
type UserOrder struct {
|
||||
Id uint64 `field:"id"` // 用户订单
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
Code string `field:"code"` // 订单号
|
||||
Type string `field:"type"` // 订单类型
|
||||
MethodId uint32 `field:"methodId"` // 支付方式
|
||||
Status string `field:"status"` // 订单状态
|
||||
Amount float64 `field:"amount"` // 金额
|
||||
Params dbs.JSON `field:"params"` // 附加参数
|
||||
ExpiredAt uint64 `field:"expiredAt"` // 过期时间
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
CancelledAt uint64 `field:"cancelledAt"` // 取消时间
|
||||
FinishedAt uint64 `field:"finishedAt"` // 结束时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type UserOrderOperator struct {
|
||||
Id interface{} // 用户订单
|
||||
UserId interface{} // 用户ID
|
||||
Code interface{} // 订单号
|
||||
Type interface{} // 订单类型
|
||||
MethodId interface{} // 支付方式
|
||||
Status interface{} // 订单状态
|
||||
Amount interface{} // 金额
|
||||
Params interface{} // 附加参数
|
||||
ExpiredAt interface{} // 过期时间
|
||||
CreatedAt interface{} // 创建时间
|
||||
CancelledAt interface{} // 取消时间
|
||||
FinishedAt interface{} // 结束时间
|
||||
State interface{} // 状态
|
||||
}
|
||||
|
||||
func NewUserOrderOperator() *UserOrderOperator {
|
||||
return &UserOrderOperator{}
|
||||
}
|
||||
1
internal/db/models/accounts/user_order_model_ext.go
Normal file
1
internal/db/models/accounts/user_order_model_ext.go
Normal file
@@ -0,0 +1 @@
|
||||
package accounts
|
||||
@@ -29,7 +29,7 @@ func init() {
|
||||
|
||||
// 创建认证信息
|
||||
func (this *ACMEAuthenticationDAO) CreateAuth(tx *dbs.Tx, taskId int64, domain string, token string, key string) error {
|
||||
op := NewACMEAuthenticationOperator()
|
||||
var op = NewACMEAuthenticationOperator()
|
||||
op.TaskId = taskId
|
||||
op.Domain = domain
|
||||
op.Token = token
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
@@ -72,8 +73,9 @@ func (this *ACMEProviderAccountDAO) FindACMEProviderAccountName(tx *dbs.Tx, id i
|
||||
}
|
||||
|
||||
// CreateAccount 创建账号
|
||||
func (this *ACMEProviderAccountDAO) CreateAccount(tx *dbs.Tx, name string, providerCode string, eabKid string, eabKey string) (int64, error) {
|
||||
func (this *ACMEProviderAccountDAO) CreateAccount(tx *dbs.Tx, userId int64, name string, providerCode string, eabKid string, eabKey string) (int64, error) {
|
||||
var op = NewACMEProviderAccountOperator()
|
||||
op.UserId = userId
|
||||
op.Name = name
|
||||
op.ProviderCode = providerCode
|
||||
op.EabKid = eabKid
|
||||
@@ -98,15 +100,18 @@ func (this *ACMEProviderAccountDAO) UpdateAccount(tx *dbs.Tx, accountId int64, n
|
||||
}
|
||||
|
||||
// CountAllEnabledAccounts 计算账号数量
|
||||
func (this *ACMEProviderAccountDAO) CountAllEnabledAccounts(tx *dbs.Tx) (int64, error) {
|
||||
func (this *ACMEProviderAccountDAO) CountAllEnabledAccounts(tx *dbs.Tx, userId int64) (int64, error) {
|
||||
return this.Query(tx).
|
||||
State(ACMEProviderAccountStateEnabled).
|
||||
Attr("userId", userId).
|
||||
Count()
|
||||
}
|
||||
|
||||
// ListEnabledAccounts 查找单页账号
|
||||
func (this *ACMEProviderAccountDAO) ListEnabledAccounts(tx *dbs.Tx, offset int64, size int64) (result []*ACMEProviderAccount, err error) {
|
||||
func (this *ACMEProviderAccountDAO) ListEnabledAccounts(tx *dbs.Tx, userId int64, offset int64, size int64) (result []*ACMEProviderAccount, err error) {
|
||||
_, err = this.Query(tx).
|
||||
State(ACMEProviderAccountStateEnabled).
|
||||
Attr("userId", userId).
|
||||
Offset(offset).
|
||||
Limit(size).
|
||||
DescPk().
|
||||
@@ -116,12 +121,34 @@ func (this *ACMEProviderAccountDAO) ListEnabledAccounts(tx *dbs.Tx, offset int64
|
||||
}
|
||||
|
||||
// FindAllEnabledAccountsWithProviderCode 根据服务商代号查找账号
|
||||
func (this *ACMEProviderAccountDAO) FindAllEnabledAccountsWithProviderCode(tx *dbs.Tx, providerCode string) (result []*ACMEProviderAccount, err error) {
|
||||
func (this *ACMEProviderAccountDAO) FindAllEnabledAccountsWithProviderCode(tx *dbs.Tx, userId int64, providerCode string) (result []*ACMEProviderAccount, err error) {
|
||||
_, err = this.Query(tx).
|
||||
State(ACMEProviderAccountStateEnabled).
|
||||
Attr("providerCode", providerCode).
|
||||
Attr("userId", userId).
|
||||
DescPk().
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
|
||||
// CheckUserAccount 检查是否为用户的服务商账号
|
||||
func (this *ACMEProviderAccountDAO) CheckUserAccount(tx *dbs.Tx, userId int64, accountId int64) error {
|
||||
if userId <= 0 || accountId <= 0 {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
b, err := this.Query(tx).
|
||||
Pk(accountId).
|
||||
State(ACMEProviderAccountStateEnabled).
|
||||
Attr("userId", userId).
|
||||
Exist()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !b {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,24 +3,26 @@ package acme
|
||||
// ACMEProviderAccount ACME提供商
|
||||
type ACMEProviderAccount struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
IsOn uint8 `field:"isOn"` // 是否启用
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
Name string `field:"name"` // 名称
|
||||
ProviderCode string `field:"providerCode"` // 代号
|
||||
Error string `field:"error"` // 最后一条错误信息
|
||||
EabKid string `field:"eabKid"` // KID
|
||||
EabKey string `field:"eabKey"` // Key
|
||||
Error string `field:"error"` // 最后一条错误信息
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type ACMEProviderAccountOperator struct {
|
||||
Id interface{} // ID
|
||||
IsOn interface{} // 是否启用
|
||||
Name interface{} // 名称
|
||||
ProviderCode interface{} // 代号
|
||||
Error interface{} // 最后一条错误信息
|
||||
EabKid interface{} // KID
|
||||
EabKey interface{} // Key
|
||||
State interface{} // 状态
|
||||
Id any // ID
|
||||
UserId any // 用户ID
|
||||
IsOn any // 是否启用
|
||||
Name any // 名称
|
||||
ProviderCode any // 代号
|
||||
EabKid any // KID
|
||||
EabKey any // Key
|
||||
Error any // 最后一条错误信息
|
||||
State any // 状态
|
||||
}
|
||||
|
||||
func NewACMEProviderAccountOperator() *ACMEProviderAccountOperator {
|
||||
|
||||
@@ -2,6 +2,7 @@ package acme
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
acmeutils "github.com/TeaOSLab/EdgeAPI/internal/acme"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
@@ -106,8 +107,17 @@ func (this *ACMETaskDAO) DisableAllTasksWithCertId(tx *dbs.Tx, certId int64) err
|
||||
}
|
||||
|
||||
// CountAllEnabledACMETasks 计算所有任务数量
|
||||
func (this *ACMETaskDAO) CountAllEnabledACMETasks(tx *dbs.Tx, adminId int64, userId int64, isAvailable bool, isExpired bool, expiringDays int64, keyword string) (int64, error) {
|
||||
query := dbutils.NewQuery(tx, this, adminId, userId)
|
||||
func (this *ACMETaskDAO) CountAllEnabledACMETasks(tx *dbs.Tx, userId int64, isAvailable bool, isExpired bool, expiringDays int64, keyword string, userOnly bool) (int64, error) {
|
||||
var query = this.Query(tx)
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
} else {
|
||||
if userOnly {
|
||||
query.Gt("userId", 0)
|
||||
} else {
|
||||
query.Attr("userId", 0)
|
||||
}
|
||||
}
|
||||
if isAvailable || isExpired || expiringDays > 0 {
|
||||
query.Gt("certId", 0)
|
||||
|
||||
@@ -125,11 +135,11 @@ func (this *ACMETaskDAO) CountAllEnabledACMETasks(tx *dbs.Tx, adminId int64, use
|
||||
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(domains LIKE :keyword)").
|
||||
Param("keyword", "%"+keyword+"%")
|
||||
Param("keyword", dbutils.QuoteLike(keyword))
|
||||
}
|
||||
if len(keyword) > 0 {
|
||||
query.Where("domains LIKE :keyword").
|
||||
Param("keyword", "%"+keyword+"%")
|
||||
Param("keyword", dbutils.QuoteLike(keyword))
|
||||
}
|
||||
|
||||
return query.State(ACMETaskStateEnabled).
|
||||
@@ -137,8 +147,17 @@ func (this *ACMETaskDAO) CountAllEnabledACMETasks(tx *dbs.Tx, adminId int64, use
|
||||
}
|
||||
|
||||
// ListEnabledACMETasks 列出单页任务
|
||||
func (this *ACMETaskDAO) ListEnabledACMETasks(tx *dbs.Tx, adminId int64, userId int64, isAvailable bool, isExpired bool, expiringDays int64, keyword string, offset int64, size int64) (result []*ACMETask, err error) {
|
||||
query := dbutils.NewQuery(tx, this, adminId, userId)
|
||||
func (this *ACMETaskDAO) ListEnabledACMETasks(tx *dbs.Tx, userId int64, isAvailable bool, isExpired bool, expiringDays int64, keyword string, userOnly bool, offset int64, size int64) (result []*ACMETask, err error) {
|
||||
var query = this.Query(tx)
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
} else {
|
||||
if userOnly {
|
||||
query.Gt("userId", 0)
|
||||
} else {
|
||||
query.Attr("userId", 0)
|
||||
}
|
||||
}
|
||||
if isAvailable || isExpired || expiringDays > 0 {
|
||||
query.Gt("certId", 0)
|
||||
|
||||
@@ -155,7 +174,7 @@ func (this *ACMETaskDAO) ListEnabledACMETasks(tx *dbs.Tx, adminId int64, userId
|
||||
}
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(domains LIKE :keyword)").
|
||||
Param("keyword", "%"+keyword+"%")
|
||||
Param("keyword", dbutils.QuoteLike(keyword))
|
||||
}
|
||||
_, err = query.
|
||||
State(ACMETaskStateEnabled).
|
||||
@@ -169,7 +188,7 @@ func (this *ACMETaskDAO) ListEnabledACMETasks(tx *dbs.Tx, adminId int64, userId
|
||||
|
||||
// CreateACMETask 创建任务
|
||||
func (this *ACMETaskDAO) CreateACMETask(tx *dbs.Tx, adminId int64, userId int64, authType acmeutils.AuthType, acmeUserId int64, dnsProviderId int64, dnsDomain string, domains []string, autoRenew bool, authURL string) (int64, error) {
|
||||
op := NewACMETaskOperator()
|
||||
var op = NewACMETaskOperator()
|
||||
op.AdminId = adminId
|
||||
op.UserId = userId
|
||||
op.AuthType = authType
|
||||
@@ -204,7 +223,7 @@ func (this *ACMETaskDAO) UpdateACMETask(tx *dbs.Tx, acmeTaskId int64, acmeUserId
|
||||
return errors.New("invalid acmeTaskId")
|
||||
}
|
||||
|
||||
op := NewACMETaskOperator()
|
||||
var op = NewACMETaskOperator()
|
||||
op.Id = acmeTaskId
|
||||
op.AcmeUserId = acmeUserId
|
||||
op.DnsProviderId = dnsProviderId
|
||||
@@ -226,21 +245,35 @@ func (this *ACMETaskDAO) UpdateACMETask(tx *dbs.Tx, acmeTaskId int64, acmeUserId
|
||||
return err
|
||||
}
|
||||
|
||||
// CheckACMETask 检查权限
|
||||
func (this *ACMETaskDAO) CheckACMETask(tx *dbs.Tx, adminId int64, userId int64, acmeTaskId int64) (bool, error) {
|
||||
return dbutils.NewQuery(tx, this, adminId, userId).
|
||||
// CheckUserACMETask 检查用户权限
|
||||
func (this *ACMETaskDAO) CheckUserACMETask(tx *dbs.Tx, userId int64, acmeTaskId int64) (bool, error) {
|
||||
var query = this.Query(tx)
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
}
|
||||
|
||||
return query.
|
||||
State(ACMETaskStateEnabled).
|
||||
Pk(acmeTaskId).
|
||||
Exist()
|
||||
}
|
||||
|
||||
// FindACMETaskUserId 查找任务所属用户ID
|
||||
func (this *ACMETaskDAO) FindACMETaskUserId(tx *dbs.Tx, taskId int64) (userId int64, err error) {
|
||||
return this.Query(tx).
|
||||
Pk(taskId).
|
||||
Result("userId").
|
||||
FindInt64Col(0)
|
||||
}
|
||||
|
||||
|
||||
// UpdateACMETaskCert 设置任务关联的证书
|
||||
func (this *ACMETaskDAO) UpdateACMETaskCert(tx *dbs.Tx, taskId int64, certId int64) error {
|
||||
if taskId <= 0 {
|
||||
return errors.New("invalid taskId")
|
||||
}
|
||||
|
||||
op := NewACMETaskOperator()
|
||||
var op = NewACMETaskOperator()
|
||||
op.Id = taskId
|
||||
op.CertId = certId
|
||||
err := this.Save(tx, op)
|
||||
@@ -271,7 +304,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
errMsg = "找不到要执行的任务"
|
||||
return
|
||||
}
|
||||
if task.IsOn != 1 {
|
||||
if !task.IsOn {
|
||||
errMsg = "任务没有启用"
|
||||
return
|
||||
}
|
||||
@@ -319,7 +352,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
return
|
||||
}
|
||||
|
||||
remoteUser := acmeutils.NewUser(user.Email, privateKey, func(resource *registration.Resource) error {
|
||||
var remoteUser = acmeutils.NewUser(user.Email, privateKey, func(resource *registration.Resource) error {
|
||||
resourceJSON, err := json.Marshal(resource)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -330,7 +363,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
})
|
||||
|
||||
if len(user.Registration) > 0 {
|
||||
err = remoteUser.SetRegistration([]byte(user.Registration))
|
||||
err = remoteUser.SetRegistration(user.Registration)
|
||||
if err != nil {
|
||||
errMsg = "设置注册信息时出错:" + err.Error()
|
||||
return
|
||||
@@ -349,7 +382,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
errMsg = "找不到DNS服务商账号"
|
||||
return
|
||||
}
|
||||
providerInterface := dnsclients.FindProvider(dnsProvider.Type)
|
||||
providerInterface := dnsclients.FindProvider(dnsProvider.Type, int64(dnsProvider.Id))
|
||||
if providerInterface == nil {
|
||||
errMsg = "暂不支持此类型的DNS服务商 '" + dnsProvider.Type + "'"
|
||||
return
|
||||
@@ -382,7 +415,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
acmeTask.Provider = acmeProvider
|
||||
acmeTask.Account = acmeAccount
|
||||
|
||||
acmeRequest := acmeutils.NewRequest(acmeTask)
|
||||
var acmeRequest = acmeutils.NewRequest(acmeTask)
|
||||
acmeRequest.OnAuth(func(domain, token, keyAuth string) {
|
||||
err := SharedACMEAuthenticationDAO.CreateAuth(tx, taskId, domain, token, keyAuth)
|
||||
if err != nil {
|
||||
@@ -398,7 +431,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
if err != nil {
|
||||
remotelogs.Error("ACME", "encode auth data failed: '"+task.AuthURL+"'")
|
||||
} else {
|
||||
client := utils.SharedHttpClient(5 * time.Second)
|
||||
var client = utils.SharedHttpClient(10 * time.Second)
|
||||
req, err := http.NewRequest(http.MethodPost, task.AuthURL, bytes.NewReader(authJSON))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", teaconst.ProductName+"/"+teaconst.Version)
|
||||
@@ -423,11 +456,11 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
}
|
||||
|
||||
// 分析证书
|
||||
sslConfig := &sslconfigs.SSLCertConfig{
|
||||
var sslConfig = &sslconfigs.SSLCertConfig{
|
||||
CertData: certData,
|
||||
KeyData: keyData,
|
||||
}
|
||||
err = sslConfig.Init()
|
||||
err = sslConfig.Init(context.Background())
|
||||
if err != nil {
|
||||
errMsg = "证书生成成功,但是分析证书信息时发生错误:" + err.Error()
|
||||
return
|
||||
@@ -453,7 +486,7 @@ func (this *ACMETaskDAO) runTaskWithoutLog(tx *dbs.Tx, taskId int64) (isOk bool,
|
||||
return
|
||||
}
|
||||
|
||||
err = models.SharedSSLCertDAO.UpdateCert(tx, resultCertId, cert.IsOn == 1, cert.Name, cert.Description, cert.ServerName, cert.IsCA == 1, certData, keyData, sslConfig.TimeBeginAt, sslConfig.TimeEndAt, sslConfig.DNSNames, sslConfig.CommonNames)
|
||||
err = models.SharedSSLCertDAO.UpdateCert(tx, resultCertId, cert.IsOn, cert.Name, cert.Description, cert.ServerName, cert.IsCA, certData, keyData, sslConfig.TimeBeginAt, sslConfig.TimeEndAt, sslConfig.DNSNames, sslConfig.CommonNames)
|
||||
if err != nil {
|
||||
errMsg = "证书生成成功,但是修改数据库中的证书信息时出错:" + err.Error()
|
||||
return
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package acme
|
||||
|
||||
import (
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
@@ -27,17 +28,17 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
// 生成日志
|
||||
// CreateACMETaskLog 生成日志
|
||||
func (this *ACMETaskLogDAO) CreateACMETaskLog(tx *dbs.Tx, taskId int64, isOk bool, errMsg string) error {
|
||||
op := NewACMETaskLogOperator()
|
||||
var op = NewACMETaskLogOperator()
|
||||
op.TaskId = taskId
|
||||
op.Error = errMsg
|
||||
op.Error = utils.LimitString(errMsg, 1024)
|
||||
op.IsOk = isOk
|
||||
err := this.Save(tx, op)
|
||||
return err
|
||||
}
|
||||
|
||||
// 取得任务的最后一条执行日志
|
||||
// FindLatestACMETasKLog 取得任务的最后一条执行日志
|
||||
func (this *ACMETaskLogDAO) FindLatestACMETasKLog(tx *dbs.Tx, taskId int64) (*ACMETaskLog, error) {
|
||||
one, err := this.Query(tx).
|
||||
Attr("taskId", taskId).
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package acme
|
||||
|
||||
// ACME任务运行日志
|
||||
// ACMETaskLog ACME任务运行日志
|
||||
type ACMETaskLog struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
TaskId uint64 `field:"taskId"` // 任务ID
|
||||
IsOk uint8 `field:"isOk"` // 是否成功
|
||||
IsOk bool `field:"isOk"` // 是否成功
|
||||
Error string `field:"error"` // 错误信息
|
||||
CreatedAt uint64 `field:"createdAt"` // 运行时间
|
||||
}
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
package acme
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// ACMETask ACME任务
|
||||
type ACMETask struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
UserId uint32 `field:"userId"` // 用户ID
|
||||
IsOn uint8 `field:"isOn"` // 是否启用
|
||||
AcmeUserId uint32 `field:"acmeUserId"` // ACME用户ID
|
||||
DnsDomain string `field:"dnsDomain"` // DNS主域名
|
||||
DnsProviderId uint64 `field:"dnsProviderId"` // DNS服务商
|
||||
Domains string `field:"domains"` // 证书域名
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
CertId uint64 `field:"certId"` // 生成的证书ID
|
||||
AutoRenew uint8 `field:"autoRenew"` // 是否自动更新
|
||||
AuthType string `field:"authType"` // 认证类型
|
||||
AuthURL string `field:"authURL"` // 认证URL
|
||||
Id uint64 `field:"id"` // ID
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
UserId uint32 `field:"userId"` // 用户ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
AcmeUserId uint32 `field:"acmeUserId"` // ACME用户ID
|
||||
DnsDomain string `field:"dnsDomain"` // DNS主域名
|
||||
DnsProviderId uint64 `field:"dnsProviderId"` // DNS服务商
|
||||
Domains dbs.JSON `field:"domains"` // 证书域名
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
CertId uint64 `field:"certId"` // 生成的证书ID
|
||||
AutoRenew uint8 `field:"autoRenew"` // 是否自动更新
|
||||
AuthType string `field:"authType"` // 认证类型
|
||||
AuthURL string `field:"authURL"` // 认证URL
|
||||
}
|
||||
|
||||
type ACMETaskOperator struct {
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"github.com/iwind/TeaGo/logs"
|
||||
)
|
||||
|
||||
// 将域名解析成字符串数组
|
||||
// DecodeDomains 将域名解析成字符串数组
|
||||
func (this *ACMETask) DecodeDomains() []string {
|
||||
if len(this.Domains) == 0 || this.Domains == "null" {
|
||||
if len(this.Domains) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := []string{}
|
||||
err := json.Unmarshal([]byte(this.Domains), &result)
|
||||
err := json.Unmarshal(this.Domains, &result)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return nil
|
||||
|
||||
@@ -83,7 +83,7 @@ func (this *ACMEUserDAO) CreateACMEUser(tx *dbs.Tx, adminId int64, userId int64,
|
||||
}
|
||||
privateKeyText := base64.StdEncoding.EncodeToString(privateKeyData)
|
||||
|
||||
op := NewACMEUserOperator()
|
||||
var op = NewACMEUserOperator()
|
||||
op.AdminId = adminId
|
||||
op.UserId = userId
|
||||
op.ProviderCode = providerCode
|
||||
@@ -104,7 +104,7 @@ func (this *ACMEUserDAO) UpdateACMEUser(tx *dbs.Tx, acmeUserId int64, descriptio
|
||||
if acmeUserId <= 0 {
|
||||
return errors.New("invalid acmeUserId")
|
||||
}
|
||||
op := NewACMEUserOperator()
|
||||
var op = NewACMEUserOperator()
|
||||
op.Id = acmeUserId
|
||||
op.Description = description
|
||||
err := this.Save(tx, op)
|
||||
@@ -116,7 +116,7 @@ func (this *ACMEUserDAO) UpdateACMEUserRegistration(tx *dbs.Tx, acmeUserId int64
|
||||
if acmeUserId <= 0 {
|
||||
return errors.New("invalid acmeUserId")
|
||||
}
|
||||
op := NewACMEUserOperator()
|
||||
var op = NewACMEUserOperator()
|
||||
op.Id = acmeUserId
|
||||
op.Registration = registrationJSON
|
||||
err := this.Save(tx, op)
|
||||
@@ -131,6 +131,8 @@ func (this *ACMEUserDAO) CountACMEUsersWithAdminId(tx *dbs.Tx, adminId int64, us
|
||||
}
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
} else {
|
||||
query.Attr("userId", 0)
|
||||
}
|
||||
if accountId > 0 {
|
||||
query.Attr("accountId", accountId)
|
||||
@@ -149,6 +151,8 @@ func (this *ACMEUserDAO) ListACMEUsers(tx *dbs.Tx, adminId int64, userId int64,
|
||||
}
|
||||
if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
} else {
|
||||
query.Attr("userId", 0)
|
||||
}
|
||||
|
||||
_, err = query.
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
package acme
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// ACMEUser ACME用户
|
||||
type ACMEUser struct {
|
||||
Id uint64 `field:"id"` // ID
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
UserId uint32 `field:"userId"` // 用户ID
|
||||
PrivateKey string `field:"privateKey"` // 私钥
|
||||
Email string `field:"email"` // E-mail
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
Description string `field:"description"` // 备注介绍
|
||||
Registration string `field:"registration"` // 注册信息
|
||||
ProviderCode string `field:"providerCode"` // 服务商代号
|
||||
AccountId uint64 `field:"accountId"` // 提供商ID
|
||||
Id uint64 `field:"id"` // ID
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
UserId uint32 `field:"userId"` // 用户ID
|
||||
PrivateKey string `field:"privateKey"` // 私钥
|
||||
Email string `field:"email"` // E-mail
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
Description string `field:"description"` // 备注介绍
|
||||
Registration dbs.JSON `field:"registration"` // 注册信息
|
||||
ProviderCode string `field:"providerCode"` // 服务商代号
|
||||
AccountId uint64 `field:"accountId"` // 提供商ID
|
||||
}
|
||||
|
||||
type ACMEUserOperator struct {
|
||||
|
||||
71
internal/db/models/ad_network_dao.go
Normal file
71
internal/db/models/ad_network_dao.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
ADNetworkStateEnabled = 1 // 已启用
|
||||
ADNetworkStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type ADNetworkDAO dbs.DAO
|
||||
|
||||
func NewADNetworkDAO() *ADNetworkDAO {
|
||||
return dbs.NewDAO(&ADNetworkDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeADNetworks",
|
||||
Model: new(ADNetwork),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*ADNetworkDAO)
|
||||
}
|
||||
|
||||
var SharedADNetworkDAO *ADNetworkDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedADNetworkDAO = NewADNetworkDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// EnableADNetwork 启用条目
|
||||
func (this *ADNetworkDAO) EnableADNetwork(tx *dbs.Tx, id uint32) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADNetworkStateEnabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// DisableADNetwork 禁用条目
|
||||
func (this *ADNetworkDAO) DisableADNetwork(tx *dbs.Tx, id int64) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADNetworkStateDisabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// FindEnabledADNetwork 查找启用中的条目
|
||||
func (this *ADNetworkDAO) FindEnabledADNetwork(tx *dbs.Tx, id int64) (*ADNetwork, error) {
|
||||
result, err := this.Query(tx).
|
||||
Pk(id).
|
||||
State(ADNetworkStateEnabled).
|
||||
Find()
|
||||
if result == nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*ADNetwork), err
|
||||
}
|
||||
|
||||
// FindADNetworkName 根据主键查找名称
|
||||
func (this *ADNetworkDAO) FindADNetworkName(tx *dbs.Tx, id uint32) (string, error) {
|
||||
return this.Query(tx).
|
||||
Pk(id).
|
||||
Result("name").
|
||||
FindStringCol("")
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package nameservers
|
||||
package models_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
24
internal/db/models/ad_network_model.go
Normal file
24
internal/db/models/ad_network_model.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
// ADNetwork 高防线路
|
||||
type ADNetwork struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
Name string `field:"name"` // 名称
|
||||
Description string `field:"description"` // 描述
|
||||
Order uint32 `field:"order"` // 排序
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type ADNetworkOperator struct {
|
||||
Id any // ID
|
||||
IsOn any // 是否启用
|
||||
Name any // 名称
|
||||
Description any // 描述
|
||||
Order any // 排序
|
||||
State any // 状态
|
||||
}
|
||||
|
||||
func NewADNetworkOperator() *ADNetworkOperator {
|
||||
return &ADNetworkOperator{}
|
||||
}
|
||||
71
internal/db/models/ad_package_dao.go
Normal file
71
internal/db/models/ad_package_dao.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
ADPackageStateEnabled = 1 // 已启用
|
||||
ADPackageStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type ADPackageDAO dbs.DAO
|
||||
|
||||
func NewADPackageDAO() *ADPackageDAO {
|
||||
return dbs.NewDAO(&ADPackageDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeADPackages",
|
||||
Model: new(ADPackage),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*ADPackageDAO)
|
||||
}
|
||||
|
||||
var SharedADPackageDAO *ADPackageDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedADPackageDAO = NewADPackageDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// EnableADPackage 启用条目
|
||||
func (this *ADPackageDAO) EnableADPackage(tx *dbs.Tx, id uint32) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADPackageStateEnabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// DisableADPackage 禁用条目
|
||||
func (this *ADPackageDAO) DisableADPackage(tx *dbs.Tx, id int64) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADPackageStateDisabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// FindEnabledADPackage 查找启用中的条目
|
||||
func (this *ADPackageDAO) FindEnabledADPackage(tx *dbs.Tx, id int64) (*ADPackage, error) {
|
||||
result, err := this.Query(tx).
|
||||
Pk(id).
|
||||
State(ADPackageStateEnabled).
|
||||
Find()
|
||||
if result == nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*ADPackage), err
|
||||
}
|
||||
|
||||
// FindADPackageName 根据主键查找名称
|
||||
func (this *ADPackageDAO) FindADPackageName(tx *dbs.Tx, id uint32) (string, error) {
|
||||
return this.Query(tx).
|
||||
Pk(id).
|
||||
Result("name").
|
||||
FindStringCol("")
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package models
|
||||
package models_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
54
internal/db/models/ad_package_instance_dao.go
Normal file
54
internal/db/models/ad_package_instance_dao.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
ADPackageInstanceStateEnabled = 1 // 已启用
|
||||
ADPackageInstanceStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type ADPackageInstanceDAO dbs.DAO
|
||||
|
||||
func NewADPackageInstanceDAO() *ADPackageInstanceDAO {
|
||||
return dbs.NewDAO(&ADPackageInstanceDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeADPackageInstances",
|
||||
Model: new(ADPackageInstance),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*ADPackageInstanceDAO)
|
||||
}
|
||||
|
||||
var SharedADPackageInstanceDAO *ADPackageInstanceDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedADPackageInstanceDAO = NewADPackageInstanceDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// EnableADPackageInstance 启用条目
|
||||
func (this *ADPackageInstanceDAO) EnableADPackageInstance(tx *dbs.Tx, id int64) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADPackageInstanceStateEnabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// FindEnabledADPackageInstance 查找启用中的条目
|
||||
func (this *ADPackageInstanceDAO) FindEnabledADPackageInstance(tx *dbs.Tx, id int64) (*ADPackageInstance, error) {
|
||||
result, err := this.Query(tx).
|
||||
Pk(id).
|
||||
State(ADPackageInstanceStateEnabled).
|
||||
Find()
|
||||
if result == nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*ADPackageInstance), err
|
||||
}
|
||||
6
internal/db/models/ad_package_instance_dao_test.go
Normal file
6
internal/db/models/ad_package_instance_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package models_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
36
internal/db/models/ad_package_instance_model.go
Normal file
36
internal/db/models/ad_package_instance_model.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package models
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// ADPackageInstance 高防实例
|
||||
type ADPackageInstance struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
PackageId uint32 `field:"packageId"` // 规格ID
|
||||
ClusterId uint32 `field:"clusterId"` // 集群ID
|
||||
NodeIds dbs.JSON `field:"nodeIds"` // 节点ID
|
||||
IpAddresses dbs.JSON `field:"ipAddresses"` // IP地址
|
||||
UserId uint64 `field:"userId"` // 用户ID
|
||||
UserDayTo string `field:"userDayTo"` // 用户有效期YYYYMMDD
|
||||
UserInstanceId uint64 `field:"userInstanceId"` // 用户实例ID
|
||||
State uint8 `field:"state"` // 状态
|
||||
ObjectCodes dbs.JSON `field:"objectCodes"` // 防护对象
|
||||
}
|
||||
|
||||
type ADPackageInstanceOperator struct {
|
||||
Id any // ID
|
||||
IsOn any // 是否启用
|
||||
PackageId any // 规格ID
|
||||
ClusterId any // 集群ID
|
||||
NodeIds any // 节点ID
|
||||
IpAddresses any // IP地址
|
||||
UserId any // 用户ID
|
||||
UserDayTo any // 用户有效期YYYYMMDD
|
||||
UserInstanceId any // 用户实例ID
|
||||
State any // 状态
|
||||
ObjectCodes any // 防护对象
|
||||
}
|
||||
|
||||
func NewADPackageInstanceOperator() *ADPackageInstanceOperator {
|
||||
return &ADPackageInstanceOperator{}
|
||||
}
|
||||
32
internal/db/models/ad_package_model.go
Normal file
32
internal/db/models/ad_package_model.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package models
|
||||
|
||||
// ADPackage 高防产品规格
|
||||
type ADPackage struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
NetworkId uint32 `field:"networkId"` // 线路ID
|
||||
ProtectionBandwidthSize uint32 `field:"protectionBandwidthSize"` // 防护带宽尺寸
|
||||
ProtectionBandwidthUnit string `field:"protectionBandwidthUnit"` // 防护带宽单位
|
||||
ProtectionBandwidthBits uint64 `field:"protectionBandwidthBits"` // 防护带宽比特
|
||||
ServerBandwidthSize uint32 `field:"serverBandwidthSize"` // 业务带宽尺寸
|
||||
ServerBandwidthUnit string `field:"serverBandwidthUnit"` // 业务带宽单位
|
||||
ServerBandwidthBits uint64 `field:"serverBandwidthBits"` // 业务带宽比特
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type ADPackageOperator struct {
|
||||
Id any // ID
|
||||
IsOn any // 是否启用
|
||||
NetworkId any // 线路ID
|
||||
ProtectionBandwidthSize any // 防护带宽尺寸
|
||||
ProtectionBandwidthUnit any // 防护带宽单位
|
||||
ProtectionBandwidthBits any // 防护带宽比特
|
||||
ServerBandwidthSize any // 业务带宽尺寸
|
||||
ServerBandwidthUnit any // 业务带宽单位
|
||||
ServerBandwidthBits any // 业务带宽比特
|
||||
State any // 状态
|
||||
}
|
||||
|
||||
func NewADPackageOperator() *ADPackageOperator {
|
||||
return &ADPackageOperator{}
|
||||
}
|
||||
63
internal/db/models/ad_package_period_dao.go
Normal file
63
internal/db/models/ad_package_period_dao.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
const (
|
||||
ADPackagePeriodStateEnabled = 1 // 已启用
|
||||
ADPackagePeriodStateDisabled = 0 // 已禁用
|
||||
)
|
||||
|
||||
type ADPackagePeriodDAO dbs.DAO
|
||||
|
||||
func NewADPackagePeriodDAO() *ADPackagePeriodDAO {
|
||||
return dbs.NewDAO(&ADPackagePeriodDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeADPackagePeriods",
|
||||
Model: new(ADPackagePeriod),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*ADPackagePeriodDAO)
|
||||
}
|
||||
|
||||
var SharedADPackagePeriodDAO *ADPackagePeriodDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedADPackagePeriodDAO = NewADPackagePeriodDAO()
|
||||
})
|
||||
}
|
||||
|
||||
// EnableADPackagePeriod 启用条目
|
||||
func (this *ADPackagePeriodDAO) EnableADPackagePeriod(tx *dbs.Tx, id uint32) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADPackagePeriodStateEnabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// DisableADPackagePeriod 禁用条目
|
||||
func (this *ADPackagePeriodDAO) DisableADPackagePeriod(tx *dbs.Tx, id int64) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Set("state", ADPackagePeriodStateDisabled).
|
||||
Update()
|
||||
return err
|
||||
}
|
||||
|
||||
// FindEnabledADPackagePeriod 查找启用中的条目
|
||||
func (this *ADPackagePeriodDAO) FindEnabledADPackagePeriod(tx *dbs.Tx, id int64) (*ADPackagePeriod, error) {
|
||||
result, err := this.Query(tx).
|
||||
Pk(id).
|
||||
State(ADPackagePeriodStateEnabled).
|
||||
Find()
|
||||
if result == nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*ADPackagePeriod), err
|
||||
}
|
||||
6
internal/db/models/ad_package_period_dao_test.go
Normal file
6
internal/db/models/ad_package_period_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package models_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
24
internal/db/models/ad_package_period_model.go
Normal file
24
internal/db/models/ad_package_period_model.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
// ADPackagePeriod 高防产品有效期
|
||||
type ADPackagePeriod struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
Count uint32 `field:"count"` // 数量
|
||||
Unit string `field:"unit"` // 单位:month, year
|
||||
Months uint32 `field:"months"` // 月数
|
||||
State uint8 `field:"state"` // 状态
|
||||
}
|
||||
|
||||
type ADPackagePeriodOperator struct {
|
||||
Id any // ID
|
||||
IsOn any // 是否启用
|
||||
Count any // 数量
|
||||
Unit any // 单位:month, year
|
||||
Months any // 月数
|
||||
State any // 状态
|
||||
}
|
||||
|
||||
func NewADPackagePeriodOperator() *ADPackagePeriodOperator {
|
||||
return &ADPackagePeriodOperator{}
|
||||
}
|
||||
1
internal/db/models/ad_package_period_model_ext.go
Normal file
1
internal/db/models/ad_package_period_model_ext.go
Normal file
@@ -0,0 +1 @@
|
||||
package models
|
||||
28
internal/db/models/ad_package_price_dao.go
Normal file
28
internal/db/models/ad_package_price_dao.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
"github.com/iwind/TeaGo/dbs"
|
||||
)
|
||||
|
||||
type ADPackagePriceDAO dbs.DAO
|
||||
|
||||
func NewADPackagePriceDAO() *ADPackagePriceDAO {
|
||||
return dbs.NewDAO(&ADPackagePriceDAO{
|
||||
DAOObject: dbs.DAOObject{
|
||||
DB: Tea.Env,
|
||||
Table: "edgeADPackagePrices",
|
||||
Model: new(ADPackagePrice),
|
||||
PkName: "id",
|
||||
},
|
||||
}).(*ADPackagePriceDAO)
|
||||
}
|
||||
|
||||
var SharedADPackagePriceDAO *ADPackagePriceDAO
|
||||
|
||||
func init() {
|
||||
dbs.OnReady(func() {
|
||||
SharedADPackagePriceDAO = NewADPackagePriceDAO()
|
||||
})
|
||||
}
|
||||
6
internal/db/models/ad_package_price_dao_test.go
Normal file
6
internal/db/models/ad_package_price_dao_test.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package models_test
|
||||
|
||||
import (
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/iwind/TeaGo/bootstrap"
|
||||
)
|
||||
22
internal/db/models/ad_package_price_model.go
Normal file
22
internal/db/models/ad_package_price_model.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package models
|
||||
|
||||
// ADPackagePrice 流量包价格
|
||||
type ADPackagePrice struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
PackageId uint32 `field:"packageId"` // 高防产品ID
|
||||
PeriodId uint32 `field:"periodId"` // 有效期ID
|
||||
Price float64 `field:"price"` // 价格
|
||||
DiscountPrice float64 `field:"discountPrice"` // 折后价格
|
||||
}
|
||||
|
||||
type ADPackagePriceOperator struct {
|
||||
Id any // ID
|
||||
PackageId any // 高防产品ID
|
||||
PeriodId any // 有效期ID
|
||||
Price any // 价格
|
||||
DiscountPrice any // 折后价格
|
||||
}
|
||||
|
||||
func NewADPackagePriceOperator() *ADPackagePriceOperator {
|
||||
return &ADPackagePriceOperator{}
|
||||
}
|
||||
1
internal/db/models/ad_package_price_model_ext.go
Normal file
1
internal/db/models/ad_package_price_model_ext.go
Normal file
@@ -0,0 +1 @@
|
||||
package models
|
||||
@@ -1,6 +1,7 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
dbutils "github.com/TeaOSLab/EdgeAPI/internal/db/utils"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/errors"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/iwind/TeaGo/Tea"
|
||||
@@ -44,11 +45,17 @@ func (this *AdminDAO) EnableAdmin(tx *dbs.Tx, id int64) (rowsAffected int64, err
|
||||
}
|
||||
|
||||
// DisableAdmin 禁用条目
|
||||
func (this *AdminDAO) DisableAdmin(tx *dbs.Tx, id int64) (rowsAffected int64, err error) {
|
||||
return this.Query(tx).
|
||||
Pk(id).
|
||||
func (this *AdminDAO) DisableAdmin(tx *dbs.Tx, adminId int64) error {
|
||||
err := this.Query(tx).
|
||||
Pk(adminId).
|
||||
Set("state", AdminStateDisabled).
|
||||
Update()
|
||||
UpdateQuickly()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除AccessTokens
|
||||
return SharedAPIAccessTokenDAO.DeleteAccessTokens(tx, adminId, 0)
|
||||
}
|
||||
|
||||
// FindEnabledAdmin 查找启用中的条目
|
||||
@@ -63,6 +70,19 @@ func (this *AdminDAO) FindEnabledAdmin(tx *dbs.Tx, id int64) (*Admin, error) {
|
||||
return result.(*Admin), err
|
||||
}
|
||||
|
||||
// FindBasicAdmin 查找管理员基本信息
|
||||
func (this *AdminDAO) FindBasicAdmin(tx *dbs.Tx, id int64) (*Admin, error) {
|
||||
result, err := this.Query(tx).
|
||||
Result("id", "username", "fullname").
|
||||
Pk(id).
|
||||
Attr("state", AdminStateEnabled).
|
||||
Find()
|
||||
if result == nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.(*Admin), err
|
||||
}
|
||||
|
||||
// ExistEnabledAdmin 检查管理员是否存在
|
||||
func (this *AdminDAO) ExistEnabledAdmin(tx *dbs.Tx, adminId int64) (bool, error) {
|
||||
return this.Query(tx).
|
||||
@@ -110,12 +130,25 @@ func (this *AdminDAO) FindAdminIdWithUsername(tx *dbs.Tx, username string) (int6
|
||||
return int64(one.(*Admin).Id), nil
|
||||
}
|
||||
|
||||
// FindAdminWithUsername 根据用户名查询管理员信息
|
||||
func (this *AdminDAO) FindAdminWithUsername(tx *dbs.Tx, username string) (*Admin, error) {
|
||||
one, err := this.Query(tx).
|
||||
Attr("username", username).
|
||||
State(AdminStateEnabled).
|
||||
ResultPk().
|
||||
Find()
|
||||
if err != nil || one == nil {
|
||||
return nil, err
|
||||
}
|
||||
return one.(*Admin), nil
|
||||
}
|
||||
|
||||
// UpdateAdminPassword 更改管理员密码
|
||||
func (this *AdminDAO) UpdateAdminPassword(tx *dbs.Tx, adminId int64, password string) error {
|
||||
if adminId <= 0 {
|
||||
return errors.New("invalid adminId")
|
||||
}
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.Id = adminId
|
||||
op.Password = stringutil.Md5(password)
|
||||
err := this.Save(tx, op)
|
||||
@@ -124,7 +157,7 @@ func (this *AdminDAO) UpdateAdminPassword(tx *dbs.Tx, adminId int64, password st
|
||||
|
||||
// CreateAdmin 创建管理员
|
||||
func (this *AdminDAO) CreateAdmin(tx *dbs.Tx, username string, canLogin bool, password string, fullname string, isSuper bool, modulesJSON []byte) (int64, error) {
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.IsOn = true
|
||||
op.State = AdminStateEnabled
|
||||
op.Username = username
|
||||
@@ -149,7 +182,7 @@ func (this *AdminDAO) UpdateAdminInfo(tx *dbs.Tx, adminId int64, fullname string
|
||||
if adminId <= 0 {
|
||||
return errors.New("invalid adminId")
|
||||
}
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.Id = adminId
|
||||
op.Fullname = fullname
|
||||
err := this.Save(tx, op)
|
||||
@@ -161,7 +194,7 @@ func (this *AdminDAO) UpdateAdmin(tx *dbs.Tx, adminId int64, username string, ca
|
||||
if adminId <= 0 {
|
||||
return errors.New("invalid adminId")
|
||||
}
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.Id = adminId
|
||||
op.Fullname = fullname
|
||||
op.Username = username
|
||||
@@ -177,10 +210,22 @@ func (this *AdminDAO) UpdateAdmin(tx *dbs.Tx, adminId int64, username string, ca
|
||||
}
|
||||
op.IsOn = isOn
|
||||
err := this.Save(tx, op)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !isOn {
|
||||
// 删除AccessTokens
|
||||
err = SharedAPIAccessTokenDAO.DeleteAccessTokens(tx, adminId, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckAdminUsername 检查用户名是否存在
|
||||
// CheckAdminUsername 检查管理员用户名是否存在
|
||||
func (this *AdminDAO) CheckAdminUsername(tx *dbs.Tx, adminId int64, username string) (bool, error) {
|
||||
query := this.Query(tx).
|
||||
State(AdminStateEnabled).
|
||||
@@ -198,7 +243,7 @@ func (this *AdminDAO) UpdateAdminLogin(tx *dbs.Tx, adminId int64, username strin
|
||||
if adminId <= 0 {
|
||||
return errors.New("invalid adminId")
|
||||
}
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.Id = adminId
|
||||
op.Username = username
|
||||
if len(password) > 0 {
|
||||
@@ -213,7 +258,7 @@ func (this *AdminDAO) UpdateAdminModules(tx *dbs.Tx, adminId int64, allowModules
|
||||
if adminId <= 0 {
|
||||
return errors.New("invalid adminId")
|
||||
}
|
||||
op := NewAdminOperator()
|
||||
var op = NewAdminOperator()
|
||||
op.Id = adminId
|
||||
op.Modules = allowModulesJSON
|
||||
err := this.Save(tx, op)
|
||||
@@ -228,24 +273,43 @@ func (this *AdminDAO) FindAllAdminModules(tx *dbs.Tx) (result []*Admin, err erro
|
||||
_, err = this.Query(tx).
|
||||
State(AdminStateEnabled).
|
||||
Attr("isOn", true).
|
||||
Result("id", "modules", "isSuper", "fullname", "theme").
|
||||
Result("id", "modules", "isSuper", "fullname", "theme", "lang").
|
||||
Slice(&result).
|
||||
FindAll()
|
||||
return
|
||||
}
|
||||
|
||||
// CountAllEnabledAdmins 计算所有管理员数量
|
||||
func (this *AdminDAO) CountAllEnabledAdmins(tx *dbs.Tx) (int64, error) {
|
||||
return this.Query(tx).
|
||||
func (this *AdminDAO) CountAllEnabledAdmins(tx *dbs.Tx, keyword string, hasWeakPasswords bool) (int64, error) {
|
||||
var query = this.Query(tx)
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(username LIKE :keyword OR fullname LIKE :keyword)")
|
||||
query.Param("keyword", dbutils.QuoteLike(keyword))
|
||||
}
|
||||
if hasWeakPasswords {
|
||||
query.Attr("password", weakPasswords)
|
||||
query.Attr("isOn", true)
|
||||
}
|
||||
return query.
|
||||
State(AdminStateEnabled).
|
||||
Count()
|
||||
}
|
||||
|
||||
// ListEnabledAdmins 列出单页的管理员
|
||||
func (this *AdminDAO) ListEnabledAdmins(tx *dbs.Tx, offset int64, size int64) (result []*Admin, err error) {
|
||||
_, err = this.Query(tx).
|
||||
func (this *AdminDAO) ListEnabledAdmins(tx *dbs.Tx, keyword string, hasWeakPasswords bool, offset int64, size int64) (result []*Admin, err error) {
|
||||
var query = this.Query(tx)
|
||||
if len(keyword) > 0 {
|
||||
query.Where("(username LIKE :keyword OR fullname LIKE :keyword)")
|
||||
query.Param("keyword", dbutils.QuoteLike(keyword))
|
||||
}
|
||||
if hasWeakPasswords {
|
||||
query.Attr("password", weakPasswords)
|
||||
query.Attr("isOn", true)
|
||||
}
|
||||
|
||||
_, err = query.
|
||||
State(AdminStateEnabled).
|
||||
Result("id", "isOn", "username", "fullname", "isSuper", "createdAt", "canLogin").
|
||||
Result("id", "isOn", "username", "fullname", "isSuper", "createdAt", "canLogin", "password").
|
||||
Offset(offset).
|
||||
Limit(size).
|
||||
DescPk().
|
||||
@@ -261,3 +325,23 @@ func (this *AdminDAO) UpdateAdminTheme(tx *dbs.Tx, adminId int64, theme string)
|
||||
Set("theme", theme).
|
||||
UpdateQuickly()
|
||||
}
|
||||
|
||||
// UpdateAdminLang 设置管理员语言
|
||||
func (this *AdminDAO) UpdateAdminLang(tx *dbs.Tx, adminId int64, langCode string) error {
|
||||
return this.Query(tx).
|
||||
Pk(adminId).
|
||||
Set("lang", langCode).
|
||||
UpdateQuickly()
|
||||
}
|
||||
|
||||
// CheckSuperAdmin 检查管理员是否为超级管理员
|
||||
func (this *AdminDAO) CheckSuperAdmin(tx *dbs.Tx, adminId int64) (bool, error) {
|
||||
if adminId <= 0 {
|
||||
return false, nil
|
||||
}
|
||||
return this.Query(tx).
|
||||
Pk(adminId).
|
||||
State(AdminStateEnabled).
|
||||
Attr("isSuper", true).
|
||||
Exist()
|
||||
}
|
||||
|
||||
@@ -1,34 +1,54 @@
|
||||
package models
|
||||
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
const (
|
||||
AdminField_Id dbs.FieldName = "id" // ID
|
||||
AdminField_IsOn dbs.FieldName = "isOn" // 是否启用
|
||||
AdminField_Username dbs.FieldName = "username" // 用户名
|
||||
AdminField_Password dbs.FieldName = "password" // 密码
|
||||
AdminField_Fullname dbs.FieldName = "fullname" // 全名
|
||||
AdminField_IsSuper dbs.FieldName = "isSuper" // 是否为超级管理员
|
||||
AdminField_CreatedAt dbs.FieldName = "createdAt" // 创建时间
|
||||
AdminField_UpdatedAt dbs.FieldName = "updatedAt" // 修改时间
|
||||
AdminField_State dbs.FieldName = "state" // 状态
|
||||
AdminField_Modules dbs.FieldName = "modules" // 允许的模块
|
||||
AdminField_CanLogin dbs.FieldName = "canLogin" // 是否可以登录
|
||||
AdminField_Theme dbs.FieldName = "theme" // 模板设置
|
||||
AdminField_Lang dbs.FieldName = "lang" // 语言代号
|
||||
)
|
||||
|
||||
// Admin 管理员
|
||||
type Admin struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn uint8 `field:"isOn"` // 是否启用
|
||||
Username string `field:"username"` // 用户名
|
||||
Password string `field:"password"` // 密码
|
||||
Fullname string `field:"fullname"` // 全名
|
||||
IsSuper uint8 `field:"isSuper"` // 是否为超级管理员
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
UpdatedAt uint64 `field:"updatedAt"` // 修改时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
Modules string `field:"modules"` // 允许的模块
|
||||
CanLogin uint8 `field:"canLogin"` // 是否可以登录
|
||||
Theme string `field:"theme"` // 模板设置
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
Username string `field:"username"` // 用户名
|
||||
Password string `field:"password"` // 密码
|
||||
Fullname string `field:"fullname"` // 全名
|
||||
IsSuper bool `field:"isSuper"` // 是否为超级管理员
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
UpdatedAt uint64 `field:"updatedAt"` // 修改时间
|
||||
State uint8 `field:"state"` // 状态
|
||||
Modules dbs.JSON `field:"modules"` // 允许的模块
|
||||
CanLogin bool `field:"canLogin"` // 是否可以登录
|
||||
Theme string `field:"theme"` // 模板设置
|
||||
Lang string `field:"lang"` // 语言代号
|
||||
}
|
||||
|
||||
type AdminOperator struct {
|
||||
Id interface{} // ID
|
||||
IsOn interface{} // 是否启用
|
||||
Username interface{} // 用户名
|
||||
Password interface{} // 密码
|
||||
Fullname interface{} // 全名
|
||||
IsSuper interface{} // 是否为超级管理员
|
||||
CreatedAt interface{} // 创建时间
|
||||
UpdatedAt interface{} // 修改时间
|
||||
State interface{} // 状态
|
||||
Modules interface{} // 允许的模块
|
||||
CanLogin interface{} // 是否可以登录
|
||||
Theme interface{} // 模板设置
|
||||
Id any // ID
|
||||
IsOn any // 是否启用
|
||||
Username any // 用户名
|
||||
Password any // 密码
|
||||
Fullname any // 全名
|
||||
IsSuper any // 是否为超级管理员
|
||||
CreatedAt any // 创建时间
|
||||
UpdatedAt any // 修改时间
|
||||
State any // 状态
|
||||
Modules any // 允许的模块
|
||||
CanLogin any // 是否可以登录
|
||||
Theme any // 模板设置
|
||||
Lang any // 语言代号
|
||||
}
|
||||
|
||||
func NewAdminOperator() *AdminOperator {
|
||||
|
||||
@@ -1 +1,42 @@
|
||||
package models
|
||||
|
||||
import stringutil "github.com/iwind/TeaGo/utils/string"
|
||||
|
||||
// 弱密码集合
|
||||
var weakPasswords = []string{}
|
||||
|
||||
func init() {
|
||||
// 初始化弱密码集合
|
||||
for _, password := range []string{
|
||||
"123",
|
||||
"1234",
|
||||
"12345",
|
||||
"123456",
|
||||
"12345678",
|
||||
"123456789",
|
||||
"000000",
|
||||
"111111",
|
||||
"666666",
|
||||
"888888",
|
||||
"654321",
|
||||
"123456789",
|
||||
"password",
|
||||
"qwerty",
|
||||
"admin",
|
||||
} {
|
||||
weakPasswords = append(weakPasswords, stringutil.Md5(password))
|
||||
}
|
||||
}
|
||||
|
||||
func (this *Admin) HasWeakPassword() bool {
|
||||
if len(this.Password) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, weakPassword := range weakPasswords {
|
||||
if weakPassword == this.Password {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func (this *APIAccessTokenDAO) GenerateAccessToken(tx *dbs.Tx, adminId int64, us
|
||||
token = rands.String(128) // TODO 增强安全性,将来使用 base64_encode(encrypt(salt+random)) 算法来代替
|
||||
expiresAt = time.Now().Unix() + 7200
|
||||
|
||||
op := NewAPIAccessTokenOperator()
|
||||
var op = NewAPIAccessTokenOperator()
|
||||
|
||||
if accessToken != nil {
|
||||
op.Id = accessToken.(*APIAccessToken).Id
|
||||
@@ -81,3 +81,16 @@ func (this *APIAccessTokenDAO) FindAccessToken(tx *dbs.Tx, token string) (*APIAc
|
||||
}
|
||||
return one.(*APIAccessToken), nil
|
||||
}
|
||||
|
||||
// DeleteAccessTokens 删除用户的令牌
|
||||
func (this *APIAccessTokenDAO) DeleteAccessTokens(tx *dbs.Tx, adminId int64, userId int64) error {
|
||||
var query = this.Query(tx)
|
||||
if adminId > 0 {
|
||||
query.Attr("adminId", adminId)
|
||||
} else if userId > 0 {
|
||||
query.Attr("userId", userId)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
return query.DeleteQuickly()
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package models
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/configs"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
@@ -49,16 +51,29 @@ func (this *APINodeDAO) EnableAPINode(tx *dbs.Tx, id int64) error {
|
||||
Pk(id).
|
||||
Set("state", APINodeStateEnabled).
|
||||
Update()
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return this.NotifyUpdate(tx, id)
|
||||
}
|
||||
|
||||
// DisableAPINode 禁用条目
|
||||
func (this *APINodeDAO) DisableAPINode(tx *dbs.Tx, id int64) error {
|
||||
func (this *APINodeDAO) DisableAPINode(tx *dbs.Tx, nodeId int64) error {
|
||||
_, err := this.Query(tx).
|
||||
Pk(id).
|
||||
Pk(nodeId).
|
||||
Set("state", APINodeStateDisabled).
|
||||
Update()
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = this.NotifyUpdate(tx, nodeId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除运行日志
|
||||
return SharedNodeLogDAO.DeleteNodeLogs(tx, nodeconfigs.NodeRoleAPI, nodeId)
|
||||
}
|
||||
|
||||
// FindEnabledAPINode 查找启用中的条目
|
||||
@@ -119,7 +134,7 @@ func (this *APINodeDAO) CreateAPINode(tx *dbs.Tx, name string, description strin
|
||||
return
|
||||
}
|
||||
|
||||
op := NewAPINodeOperator()
|
||||
var op = NewAPINodeOperator()
|
||||
op.IsOn = isOn
|
||||
op.UniqueId = uniqueId
|
||||
op.Secret = secret
|
||||
@@ -149,16 +164,33 @@ func (this *APINodeDAO) CreateAPINode(tx *dbs.Tx, name string, description strin
|
||||
return
|
||||
}
|
||||
|
||||
err = this.NotifyUpdate(tx, types.Int64(op.Id))
|
||||
if err != nil {
|
||||
remotelogs.Error("API_NODE_DAO", err.Error())
|
||||
}
|
||||
|
||||
return types.Int64(op.Id), nil
|
||||
}
|
||||
|
||||
// UpdateAPINode 修改API节点
|
||||
func (this *APINodeDAO) UpdateAPINode(tx *dbs.Tx, nodeId int64, name string, description string, httpJSON []byte, httpsJSON []byte, restIsOn bool, restHTTPJSON []byte, restHTTPSJSON []byte, accessAddrsJSON []byte, isOn bool) error {
|
||||
func (this *APINodeDAO) UpdateAPINode(tx *dbs.Tx, nodeId int64, name string, description string, httpJSON []byte, httpsJSON []byte, restIsOn bool, restHTTPJSON []byte, restHTTPSJSON []byte, accessAddrsJSON []byte, isOn bool, isPrimary bool) error {
|
||||
if nodeId <= 0 {
|
||||
return errors.New("invalid nodeId")
|
||||
}
|
||||
|
||||
op := NewAPINodeOperator()
|
||||
// 取消别的Primary
|
||||
if isPrimary {
|
||||
err := this.Query(tx).
|
||||
Neq("id", nodeId).
|
||||
Attr("isPrimary", true).
|
||||
Set("isPrimary", false).
|
||||
UpdateQuickly()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var op = NewAPINodeOperator()
|
||||
op.Id = nodeId
|
||||
op.Name = name
|
||||
op.Description = description
|
||||
@@ -191,8 +223,13 @@ func (this *APINodeDAO) UpdateAPINode(tx *dbs.Tx, nodeId int64, name string, des
|
||||
op.AccessAddrs = "[]"
|
||||
}
|
||||
|
||||
op.IsPrimary = isPrimary
|
||||
|
||||
err := this.Save(tx, op)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return this.NotifyUpdate(tx, nodeId)
|
||||
}
|
||||
|
||||
// FindAllEnabledAPINodes 列出所有可用API节点
|
||||
@@ -294,27 +331,11 @@ func (this *APINodeDAO) UpdateAPINodeStatus(tx *dbs.Tx, apiNodeId int64, statusJ
|
||||
return err
|
||||
}
|
||||
|
||||
// 生成唯一ID
|
||||
func (this *APINodeDAO) genUniqueId(tx *dbs.Tx) (string, error) {
|
||||
for {
|
||||
uniqueId := rands.HexString(32)
|
||||
ok, err := this.Query(tx).
|
||||
Attr("uniqueId", uniqueId).
|
||||
Exist()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
return uniqueId, nil
|
||||
}
|
||||
}
|
||||
|
||||
// CountAllLowerVersionNodes 计算所有节点中低于某个版本的节点数量
|
||||
func (this *APINodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
|
||||
return this.Query(tx).
|
||||
State(APINodeStateEnabled).
|
||||
Attr("isOn", true).
|
||||
Where("status IS NOT NULL").
|
||||
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
|
||||
Param("version", utils.VersionToLong(version)).
|
||||
@@ -384,3 +405,114 @@ func (this *APINodeDAO) FindAllEnabledAPIAccessIPs(tx *dbs.Tx, cacheMap *utils.C
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// CheckAPINodeIsPrimary 检查当前节点是否为Primary节点
|
||||
func (this *APINodeDAO) CheckAPINodeIsPrimary(tx *dbs.Tx) (bool, error) {
|
||||
config, err := configs.SharedAPIConfig()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
isPrimary, err := this.Query(tx).
|
||||
State(APINodeStateEnabled).
|
||||
Attr("uniqueId", config.NodeId).
|
||||
Attr("isPrimary", true).
|
||||
Exist()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if isPrimary {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 检查是否有别的Primary节点
|
||||
count, err := this.Query(tx).
|
||||
State(APINodeStateEnabled).
|
||||
Attr("isOn", true).
|
||||
Attr("isPrimary", true).
|
||||
Count()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
err = this.ResetPrimaryAPINode(tx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// CheckAPINodeIsPrimaryWithoutErr 检查当前节点是否为Primary节点,并忽略错误
|
||||
func (this *APINodeDAO) CheckAPINodeIsPrimaryWithoutErr() bool {
|
||||
b, err := this.CheckAPINodeIsPrimary(nil)
|
||||
return b && err == nil
|
||||
}
|
||||
|
||||
// ResetPrimaryAPINode 重置Primary节点
|
||||
func (this *APINodeDAO) ResetPrimaryAPINode(tx *dbs.Tx) error {
|
||||
// 当前是否有Primary节点
|
||||
apiNode, err := this.Query(tx).
|
||||
State(APINodeStateEnabled).
|
||||
Attr("isOn", true).
|
||||
Attr("isPrimary", true).
|
||||
Find()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if apiNode == nil {
|
||||
// 选择一个作为Primary
|
||||
// TODO 将来需要考虑API节点离线的情况
|
||||
apiNodeId, err := this.Query(tx).
|
||||
State(APINodeStateEnabled).
|
||||
Attr("isOn", true).
|
||||
ResultPk().
|
||||
FindInt64Col(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if apiNodeId > 0 {
|
||||
err = this.Query(tx).
|
||||
Pk(apiNodeId).
|
||||
Set("isPrimary", true).
|
||||
UpdateQuickly()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyUpdate 通知变更
|
||||
func (this *APINodeDAO) NotifyUpdate(tx *dbs.Tx, apiNodeId int64) error {
|
||||
// suppress IDE warning
|
||||
_ = apiNodeId
|
||||
|
||||
err := this.ResetPrimaryAPINode(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 生成唯一ID
|
||||
func (this *APINodeDAO) genUniqueId(tx *dbs.Tx) (string, error) {
|
||||
for {
|
||||
uniqueId := rands.HexString(32)
|
||||
ok, err := this.Query(tx).
|
||||
Attr("uniqueId", uniqueId).
|
||||
Exist()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
return uniqueId, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,16 @@ func TestAPINodeDAO_FindAllEnabledAPIAccessIPs(t *testing.T) {
|
||||
t.Log(NewAPINodeDAO().FindAllEnabledAPIAccessIPs(nil, cacheMap))
|
||||
}
|
||||
|
||||
func TestAPINodeDAO_CheckAPINodeIsPrimary(t *testing.T) {
|
||||
var dao = NewAPINodeDAO()
|
||||
t.Log(dao.CheckAPINodeIsPrimary(nil))
|
||||
}
|
||||
|
||||
func TestAPINodeDAO_ResetPrimaryAPINode(t *testing.T) {
|
||||
var dao = NewAPINodeDAO()
|
||||
t.Log(dao.ResetPrimaryAPINode(nil))
|
||||
}
|
||||
|
||||
func BenchmarkAPINodeDAO_New(b *testing.B) {
|
||||
runtime.GOMAXPROCS(1)
|
||||
for i := 0; i < b.N; i++ {
|
||||
|
||||
@@ -1,26 +1,29 @@
|
||||
package models
|
||||
|
||||
// API节点
|
||||
import "github.com/iwind/TeaGo/dbs"
|
||||
|
||||
// APINode API节点
|
||||
type APINode struct {
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn uint8 `field:"isOn"` // 是否启用
|
||||
ClusterId uint32 `field:"clusterId"` // 专用集群ID
|
||||
UniqueId string `field:"uniqueId"` // 唯一ID
|
||||
Secret string `field:"secret"` // 密钥
|
||||
Name string `field:"name"` // 名称
|
||||
Description string `field:"description"` // 描述
|
||||
Http string `field:"http"` // 监听的HTTP配置
|
||||
Https string `field:"https"` // 监听的HTTPS配置
|
||||
RestIsOn uint8 `field:"restIsOn"` // 是否开放REST
|
||||
RestHTTP string `field:"restHTTP"` // REST HTTP配置
|
||||
RestHTTPS string `field:"restHTTPS"` // REST HTTPS配置
|
||||
AccessAddrs string `field:"accessAddrs"` // 外部访问地址
|
||||
Order uint32 `field:"order"` // 排序
|
||||
State uint8 `field:"state"` // 状态
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
Weight uint32 `field:"weight"` // 权重
|
||||
Status string `field:"status"` // 运行状态
|
||||
Id uint32 `field:"id"` // ID
|
||||
IsOn bool `field:"isOn"` // 是否启用
|
||||
ClusterId uint32 `field:"clusterId"` // 专用集群ID
|
||||
UniqueId string `field:"uniqueId"` // 唯一ID
|
||||
Secret string `field:"secret"` // 密钥
|
||||
Name string `field:"name"` // 名称
|
||||
Description string `field:"description"` // 描述
|
||||
Http dbs.JSON `field:"http"` // 监听的HTTP配置
|
||||
Https dbs.JSON `field:"https"` // 监听的HTTPS配置
|
||||
RestIsOn uint8 `field:"restIsOn"` // 是否开放REST
|
||||
RestHTTP dbs.JSON `field:"restHTTP"` // REST HTTP配置
|
||||
RestHTTPS dbs.JSON `field:"restHTTPS"` // REST HTTPS配置
|
||||
AccessAddrs dbs.JSON `field:"accessAddrs"` // 外部访问地址
|
||||
Order uint32 `field:"order"` // 排序
|
||||
State uint8 `field:"state"` // 状态
|
||||
CreatedAt uint64 `field:"createdAt"` // 创建时间
|
||||
AdminId uint32 `field:"adminId"` // 管理员ID
|
||||
Weight uint32 `field:"weight"` // 权重
|
||||
Status dbs.JSON `field:"status"` // 运行状态
|
||||
IsPrimary bool `field:"isPrimary"` // 是否为主API节点
|
||||
}
|
||||
|
||||
type APINodeOperator struct {
|
||||
@@ -43,6 +46,7 @@ type APINodeOperator struct {
|
||||
AdminId interface{} // 管理员ID
|
||||
Weight interface{} // 权重
|
||||
Status interface{} // 运行状态
|
||||
IsPrimary interface{} // 是否为主API节点
|
||||
}
|
||||
|
||||
func NewAPINodeOperator() *APINodeOperator {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user