-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathuser.go
332 lines (292 loc) · 11.3 KB
/
user.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package lobster
import "github.com/asaskevich/govalidator"
import "fmt"
import "time"
type User struct {
Id int
Username string
Email string
CreateTime time.Time
Credit int64
VmLimit int
LastBillingNotify time.Time
Status string
Admin bool
}
type Charge struct {
Id int
UserId int
Name string
Detail string
Key string
Time time.Time
Amount int64
}
func UserList() []*User {
var users []*User
rows := db.Query("SELECT id, username, email, time_created, credit, vm_limit, last_billing_notify, status, admin FROM users ORDER BY id")
defer rows.Close()
for rows.Next() {
user := &User{}
rows.Scan(&user.Id, &user.Username, &user.Email, &user.CreateTime, &user.Credit, &user.VmLimit, &user.LastBillingNotify, &user.Status, &user.Admin)
users = append(users, user)
}
return users
}
func UserDetails(userId int) *User {
user := &User{}
rows := db.Query("SELECT id, username, email, time_created, credit, vm_limit, last_billing_notify, status, admin FROM users WHERE id = ?", userId)
if !rows.Next() {
return nil
}
rows.Scan(&user.Id, &user.Username, &user.Email, &user.CreateTime, &user.Credit, &user.VmLimit, &user.LastBillingNotify, &user.Status, &user.Admin)
rows.Close()
return user
}
func UserCreate(username string, password string, email string) (int, error) {
if email != "" && !govalidator.IsEmail(email) {
return 0, L.Error("invalid_email")
}
if len(username) < MIN_USERNAME_LENGTH || len(username) > MAX_USERNAME_LENGTH {
return 0, L.Errorf("username_length", MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH)
}
if !isPrintable(username) {
return 0, L.Error("invalid_username_format")
}
if len(password) < MIN_PASSWORD_LENGTH || len(password) > MAX_PASSWORD_LENGTH {
return 0, L.Errorf("password_length", MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
}
// ensure username not taken already
var userCount int
db.QueryRow("SELECT COUNT(*) FROM users WHERE username = ?", username).Scan(&userCount)
if userCount > 0 {
return 0, L.Error("username_in_use")
}
// ensure email not taken already
if email != "" {
db.QueryRow("SELECT COUNT(*) FROM users WHERE email = ?", email).Scan(&userCount)
if userCount > 0 {
return 0, L.Error("email_in_use")
}
}
// generate salt and hash password
result := db.Exec("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", username, authMakePassword(password), email)
return result.LastInsertId(), nil
}
func ChargeList(userId int, year int, month time.Month) []*Charge {
timeStart := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
timeEnd := timeStart.AddDate(0, 1, 0)
var charges []*Charge
rows := db.Query("SELECT id, user_id, name, detail, k, time, amount FROM charges WHERE user_id = ? AND time >= ? AND time < ? ORDER BY time", userId, timeStart.Format(MYSQL_TIME_FORMAT), timeEnd.Format(MYSQL_TIME_FORMAT))
defer rows.Close()
for rows.Next() {
charge := Charge{}
rows.Scan(&charge.Id, &charge.UserId, &charge.Name, &charge.Detail, &charge.Key, &charge.Time, &charge.Amount)
charges = append(charges, &charge)
}
return charges
}
func UserApplyCredit(userId int, amount int64, detail string) {
db.Exec("INSERT INTO charges (user_id, name, time, amount, detail) VALUES (?, ?, CURDATE(), ?, ?)", userId, "Credit updated", -amount, detail)
db.Exec("UPDATE users SET status = 'active' WHERE id = ? AND status = 'new'", userId)
userAdjustCredit(userId, amount)
user := UserDetails(userId)
if user.Credit > 0 {
vms := vmList(userId)
for _, vm := range vms {
if vm.Suspended == "auto" {
ReportError(vm.Unsuspend(), "failed to unsuspend VM", fmt.Sprintf("user_id: %d, vm_id: %d", userId, vm.Id))
MailWrap(userId, "vmUnsuspend", VmUnsuspendEmail{Name: vm.Name}, false)
}
}
}
}
func UserApplyCharge(userId int, name string, detail string, k string, amount int64) {
rows := db.Query("SELECT id FROM charges WHERE user_id = ? AND k = ? AND time = CURDATE()", userId, k)
if rows.Next() {
var chargeId int
rows.Scan(&chargeId)
rows.Close()
db.Exec("UPDATE charges SET amount = amount + ? WHERE id = ?", amount, chargeId)
} else {
db.Exec("INSERT INTO charges (user_id, name, amount, time, detail, k) VALUES (?, ?, ?, CURDATE(), ?, ?)", userId, name, amount, detail, k)
}
userAdjustCredit(userId, -amount)
}
func userAdjustCredit(userId int, amount int64) {
db.Exec("UPDATE users SET credit = credit + ? WHERE id = ?", amount, userId)
}
type CreditSummary struct {
Credit int64
Hourly int64
Daily int64
Monthly int64
DaysRemaining string
Status string
}
func UserCreditSummary(userId int) *CreditSummary {
user := UserDetails(userId)
if user == nil {
return nil
}
summary := CreditSummary{Credit: user.Credit}
vms := vmList(userId)
for _, vm := range vms {
summary.Hourly += vm.Plan.Price
}
summary.Daily = summary.Hourly * 24
summary.Monthly = summary.Daily * 30
// calculate days remaining
if summary.Daily > 0 {
daysRemaining := int(summary.Credit / summary.Daily)
summary.DaysRemaining = fmt.Sprintf("%d", daysRemaining)
if daysRemaining < 1 {
summary.Status = "danger"
} else if daysRemaining < 7 {
summary.Status = "warning"
} else {
summary.Status = "success"
}
} else {
summary.DaysRemaining = "infinite"
summary.Status = "success"
}
return &summary
}
type BandwidthSummary struct {
Used int64
Allocated int64
Billed int64
NotifiedPercent int
ActualPercent float64
}
func UserBandwidthSummary(userId int) map[string]*BandwidthSummary {
now := time.Now()
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
monthEnd := monthStart.AddDate(0, 1, 0)
bw := make(map[string]*BandwidthSummary)
rows := db.Query("SELECT region, bandwidth_used, bandwidth_additional, bandwidth_billed, bandwidth_notified_percent FROM region_bandwidth WHERE user_id = ?", userId)
defer rows.Close()
for rows.Next() {
var region string
summary := BandwidthSummary{}
rows.Scan(®ion, &summary.Used, &summary.Allocated, &summary.Billed, &summary.NotifiedPercent)
bw[region] = &summary
// add in bandwidth from active vms in this region
// each one adds bandwidth proportional to the time it was provisioned relative to beginning of month
for _, vm := range vmListRegion(userId, region) {
planBandwidthBytes := gigaToBytes(vm.Plan.Bandwidth)
if vm.CreatedTime.After(monthStart) {
timeRemaining := monthEnd.Sub(vm.CreatedTime)
if timeRemaining > 0 {
activeRatio := float64(timeRemaining) / float64(monthEnd.Sub(monthStart))
bw[region].Allocated += int64(float64(planBandwidthBytes) * activeRatio)
}
} else {
bw[region].Allocated += planBandwidthBytes
}
}
bw[region].ActualPercent = 100 * float64(bw[region].Used) / float64(bw[region].Allocated)
}
return bw
}
func userBilling(userId int) {
// bill/notify for bandwidth usage
creditPerGB := int64(cfg.Billing.BandwidthOverageFee * BILLING_PRECISION)
for region, summary := range UserBandwidthSummary(userId) {
if summary.Used > gigaToBytes(200) {
// first do billing
// we provide some leeway on bandwidth to avoid confusion in edge cases
// for example, if user provisions new VM, installs packages, and then deletes it,
// then they might go over their bandwidth limit (since it's proportional)
// it is correct to charge them in this case, but if it's a small amount of bandwidth then the possible confusion isn't worth it
// also we only bill in multiples of 1 GB (TODO: maybe store it as GB instead of bytes?)
if summary.Used > summary.Allocated+gigaToBytes(50) {
gbOver := int((summary.Used - summary.Allocated - summary.Billed) / 1024 / 1024 / 1024)
if gbOver > 0 {
UserApplyCharge(userId, "Bandwidth", fmt.Sprintf("Bandwidth usage overage charge %s ($%.4f/GB)", region, cfg.Billing.BandwidthOverageFee), "bw-"+region, creditPerGB*int64(gbOver))
db.Exec("UPDATE region_bandwidth SET bandwidth_billed = bandwidth_billed + ? WHERE user_id = ? AND region = ?", gigaToBytes(gbOver), userId, region)
}
}
// now bandwidth usage notifications
// we notify on:
// changes in percentage exceeding 5
// actual overage event (>100%)
// also if user provisioned more VM, was no longer over bandwidth, but now is going over again
if summary.Allocated != 0 {
utilPercent := int((100 * summary.Used) / summary.Allocated)
if summary.NotifiedPercent < 100 && utilPercent > 85 && (utilPercent-summary.NotifiedPercent >= 5 || (summary.NotifiedPercent < 100 && utilPercent >= 100) || utilPercent < summary.NotifiedPercent) {
db.Exec("UPDATE region_bandwidth SET bandwidth_notified_percent = ? WHERE user_id = ? AND region = ?", utilPercent, userId, region)
tmpl := "bandwidthNotify"
if utilPercent >= 100 {
tmpl = "bandwidthOverage"
}
emailParams := BandwidthUsageEmail{
UtilPercent: utilPercent,
Region: region,
Fee: creditPerGB,
}
MailWrap(userId, tmpl, emailParams, false)
}
}
}
}
// check for low account balance, possibly suspend/terminate virtual machines
rows := db.Query(
"SELECT credit, email, IFNULL(TIMESTAMPDIFF(HOUR, last_billing_notify, NOW()), 0), billing_low_count "+
"FROM users "+
"WHERE id = ? AND last_billing_notify < DATE_SUB(NOW(), INTERVAL ? HOUR) AND "+
"(SELECT COUNT(*) FROM vms WHERE vms.user_id = users.id) > 0",
userId,
cfg.BillingNotifications.Frequency,
)
if !rows.Next() {
return
}
var credit int64
var email string
var lastBilledHoursAgo int // how many hours ago this user was last billed
var billingLowCount int // how many reminders regarding low account balance have been sent
rows.Scan(&credit, &email, &lastBilledHoursAgo, &billingLowCount)
rows.Close()
hourly := UserCreditSummary(userId).Hourly
if credit <= hourly*int64(cfg.BillingNotifications.LowBalanceIntervals) {
canSuspendBalance := credit < hourly*int64(cfg.BillingTermination.SuspendBalanceIntervals)
canSuspendNotifications := billingLowCount >= cfg.BillingTermination.SuspendMinNotifications
if canSuspendBalance && canSuspendNotifications {
canTerminateBalance := credit < hourly*int64(cfg.BillingTermination.TerminateBalanceIntervals)
canTerminateNotifications := billingLowCount >= cfg.BillingTermination.TerminateMinNotifications
if canTerminateBalance && canTerminateNotifications && lastBilledHoursAgo > 0 && lastBilledHoursAgo <= 48 {
// terminte the account
vms := vmList(userId)
for _, vm := range vms {
ReportError(vm.Delete(userId), "failed to delete VM", fmt.Sprintf("user_id: %d, vm_id: %d", userId, vm.Id))
}
MailWrap(userId, "userTerminate", nil, false)
} else {
// suspend
vms := vmList(userId)
for _, vm := range vms {
vm.Suspend(true)
}
MailWrap(userId, "userSuspend", nil, false)
}
} else {
// send low credit warning
remainingHours := int(credit / hourly)
params := LowCreditEmail{
Credit: credit,
Hourly: hourly,
RemainingHours: remainingHours,
}
tmpl := "userLowCredit"
if credit < 0 {
tmpl = "userNegativeCredit"
}
MailWrap(userId, tmpl, params, false)
}
db.Exec("UPDATE users SET last_billing_notify = NOW(), billing_low_count = billing_low_count + 1 WHERE id = ?", userId)
} else {
db.Exec("UPDATE users SET last_billing_notify = NOW(), billing_low_count = 0 WHERE id = ?", userId)
}
}