forked from zhanggf2010/v2ray-ssrpanel-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
panel.go
275 lines (234 loc) · 6.49 KB
/
panel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package ssrpanel
import (
"code.cloudfoundry.org/bytefmt"
"fmt"
"github.com/jinzhu/gorm"
"github.com/robfig/cron"
"github.com/shirou/gopsutil/load"
"google.golang.org/grpc"
"time"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/vmess"
)
type Panel struct {
*Config
handlerServiceClient *HandlerServiceClient
statsServiceClient *StatsServiceClient
db *DB
userModels []UserModel
startAt time.Time
node *Node
}
func NewPanel(gRPCConn *grpc.ClientConn, db *DB, cfg *Config) (*Panel, error) {
node, err := db.GetNode(cfg.NodeID)
if err != nil {
return nil, err
}
newErrorf("node[%d] traffic rate %.2f", node.ID, node.TrafficRate).AtDebug().WriteToLog()
return &Panel{
Config: cfg,
db: db,
handlerServiceClient: NewHandlerServiceClient(gRPCConn, cfg.UserConfig.InboundTag),
statsServiceClient: NewStatsServiceClient(gRPCConn),
startAt: time.Now(),
node: node,
}, nil
}
func (p *Panel) Start() {
doFunc := func() {
if err := p.do(); err != nil {
newError("panel#do").Base(err).AtError().WriteToLog()
}
}
doFunc()
c := cron.New()
c.AddFunc(fmt.Sprintf("@every %ds", p.CheckRate), doFunc)
c.Start()
c.Run()
}
func (p *Panel) do() error {
var addedUserCount, deletedUserCount, onlineUsers int
var uplinkTotal, downlinkTotal uint64
if err := p.db.DB.DB().Ping(); err != nil {
p.db.RetryTimes++
newErrorf("Lost db connection, retry times: %d",
p.db.RetryTimes).AtDebug().WriteToLog()
return nil
}
p.db.RetryTimes = 0
defer func() {
newErrorf("+ %d users, - %d users, ↓ %s, ↑ %s, online %d",
addedUserCount, deletedUserCount, bytefmt.ByteSize(downlinkTotal), bytefmt.ByteSize(uplinkTotal), onlineUsers).AtDebug().WriteToLog()
}()
if err := p.db.DB.Create(&NodeInfo{
NodeID: p.NodeID,
Uptime: time.Now().Sub(p.startAt) / time.Second,
Load: getSystemLoad(),
}).Error; err != nil {
return err
}
userTrafficLogs, err := p.getTraffic()
if err != nil {
return err
}
onlineUsers = len(userTrafficLogs)
var uVals, dVals string
var userIDs []uint
for _, log := range userTrafficLogs {
uplink := p.mulTrafficRate(log.Uplink)
downlink := p.mulTrafficRate(log.Downlink)
uplinkTotal += log.Uplink
downlinkTotal += log.Downlink
log.Traffic = bytefmt.ByteSize(uplink + downlink)
p.db.DB.Create(&log.UserTrafficLog)
userIDs = append(userIDs, log.UserID)
uVals += fmt.Sprintf(" WHEN %d THEN u + %d", log.UserID, uplink)
dVals += fmt.Sprintf(" WHEN %d THEN d + %d", log.UserID, downlink)
if log.ipList != "" {
p.db.DB.Create(&NodeIP{
NodeID: log.NodeID,
UserID: log.UserID,
IPList: log.ipList,
Port: log.UserPort,
})
}
}
if onlineUsers > 0 {
p.db.DB.Create(&NodeOnlineLog{
NodeID: p.NodeID,
OnlineUser: onlineUsers,
})
}
if uVals != "" && dVals != "" {
p.db.DB.Table("user").
Where("id in (?)", userIDs).
Updates(map[string]interface{}{
"u": gorm.Expr(fmt.Sprintf("CASE id %s END", uVals)),
"d": gorm.Expr(fmt.Sprintf("CASE id %s END", dVals)),
"t": time.Now().Unix(),
})
}
addedUserCount, deletedUserCount, err = p.syncUser()
return nil
}
type userStatsLogs struct {
UserTrafficLog
ipList string
UserPort int
}
func (p *Panel) getTraffic() (logs []userStatsLogs, err error) {
var downlink, uplink uint64
var ips string
for _, user := range p.userModels {
downlink, err = p.statsServiceClient.getUserDownlink(user.Email)
if err != nil {
return
}
uplink, err = p.statsServiceClient.getUserUplink(user.Email)
if err != nil {
return
}
if uplink+downlink > 0 {
ips, err = p.statsServiceClient.getUserIPStats(user.Email, true)
if err != nil {
return
}
logs = append(logs, userStatsLogs{
UserTrafficLog: UserTrafficLog{
UserID: user.ID,
Uplink: uplink,
Downlink: downlink,
NodeID: p.NodeID,
Rate: p.node.TrafficRate,
},
ipList: ips,
UserPort: user.Port,
})
}
}
return
}
func (p *Panel) mulTrafficRate(traffic uint64) uint64 {
return uint64(p.node.TrafficRate * float64(traffic))
}
func (p *Panel) syncUser() (addedUserCount, deletedUserCount int, err error) {
userModels, err := p.db.GetAllUsers()
if err != nil {
return 0, 0, err
}
if len(userModels) == 0 {
return 0, 0, err
}
// Calculate addition users
addUserModels := make([]UserModel, 0)
for _, userModel := range userModels {
if inUserModels(&userModel, p.userModels) {
continue
}
addUserModels = append(addUserModels, userModel)
}
// Calculate deletion users
delUserModels := make([]UserModel, 0)
for _, userModel := range p.userModels {
if inUserModels(&userModel, userModels) {
continue
}
delUserModels = append(delUserModels, userModel)
}
// Delete
for _, userModel := range delUserModels {
if i := findUserModelIndex(&userModel, p.userModels); i != -1 {
p.userModels = append(p.userModels[:i], p.userModels[i+1:]...)
if err = p.handlerServiceClient.DelUser(userModel.Email); err != nil {
return
}
deletedUserCount++
newErrorf("Deleted user: id=%d, VmessID=%s, Email=%s", userModel.ID, userModel.VmessID, userModel.Email).AtDebug().WriteToLog()
}
}
// Add
for _, userModel := range addUserModels {
if err = p.handlerServiceClient.AddUser(p.convertUser(userModel)); err != nil {
if p.IgnoreEmptyVmessID {
newErrorf("add user err \"%s\" user: %#v", err, userModel).AtWarning().WriteToLog()
continue
}
fatal("add user err ", err, userModel)
}
p.userModels = append(p.userModels, userModel)
addedUserCount++
newErrorf("Added user: id=%d, VmessID=%s, Email=%s", userModel.ID, userModel.VmessID, userModel.Email).AtDebug().WriteToLog()
}
return
}
func (p *Panel) convertUser(userModel UserModel) *protocol.User {
userCfg := p.UserConfig
return &protocol.User{
Level: userCfg.Level,
Email: userModel.Email,
Account: serial.ToTypedMessage(&vmess.Account{
Id: userModel.VmessID,
AlterId: userCfg.AlterID,
SecuritySettings: userCfg.securityConfig,
}),
}
}
func findUserModelIndex(u *UserModel, userModels []UserModel) int {
for i, user := range userModels {
if user == *u {
return i
}
}
return -1
}
func inUserModels(u *UserModel, userModels []UserModel) bool {
return findUserModelIndex(u, userModels) != -1
}
func getSystemLoad() string {
stat, err := load.Avg()
if err != nil {
return "0.00 0.00 0.00"
}
return fmt.Sprintf("%.2f %.2f %.2f", stat.Load1, stat.Load5, stat.Load15)
}