/
dashboard.go
295 lines (251 loc) · 11.2 KB
/
dashboard.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
package panel
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"runtime"
"strconv"
"sync"
"sync/atomic"
"time"
c "github.com/Azareal/Gosora/common"
p "github.com/Azareal/Gosora/common/phrases"
qgen "github.com/Azareal/Gosora/query_gen"
"github.com/Azareal/gopsutil/mem"
"github.com/pkg/errors"
)
type dashStmts struct {
todaysPostCount *sql.Stmt
todaysTopicCount *sql.Stmt
todaysTopicCountByForum *sql.Stmt
todaysNewUserCount *sql.Stmt
weeklyTopicCountByForum *sql.Stmt
}
// TODO: Stop hard-coding these queries
func dashMySQLStmts() (stmts dashStmts, err error) {
db := qgen.Builder.GetConn()
prepStmt := func(table, ext, dur string) *sql.Stmt {
if err != nil {
return nil
}
stmt, ierr := db.Prepare("select count(*) from " + table + " where createdAt BETWEEN (utc_timestamp() - interval 1 " + dur + ") and utc_timestamp() " + ext)
err = errors.WithStack(ierr)
return stmt
}
stmts.todaysPostCount = prepStmt("replies", "", "day")
stmts.todaysTopicCount = prepStmt("topics", "", "day")
stmts.todaysNewUserCount = prepStmt("users", "", "day")
stmts.todaysTopicCountByForum = prepStmt("topics", " and parentID=?", "day")
stmts.weeklyTopicCountByForum = prepStmt("topics", " and parentID=?", "week")
return stmts, err
}
// TODO: Stop hard-coding these queries
func dashMSSQLStmts() (stmts dashStmts, err error) {
db := qgen.Builder.GetConn()
prepStmt := func(table, ext, dur string) *sql.Stmt {
if err != nil {
return nil
}
stmt, ierr := db.Prepare("select count(*) from " + table + " where createdAt >= DATEADD(" + dur + ", -1, GETUTCDATE())" + ext)
err = errors.WithStack(ierr)
return stmt
}
stmts.todaysPostCount = prepStmt("replies", "", "DAY")
stmts.todaysTopicCount = prepStmt("topics", "", "DAY")
stmts.todaysNewUserCount = prepStmt("users", "", "DAY")
stmts.todaysTopicCountByForum = prepStmt("topics", " and parentID=?", "DAY")
stmts.weeklyTopicCountByForum = prepStmt("topics", " and parentID=?", "WEEK")
return stmts, err
}
type GE = c.GridElement
func Dashboard(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, user, "dashboard", "dashboard")
if ferr != nil {
return ferr
}
unknown := p.GetTmplPhrase("panel_dashboard_unknown")
// We won't calculate this on the spot anymore, as the system doesn't seem to like it if we do multiple fetches simultaneously. Should we constantly calculate this on a background thread? Perhaps, the watchdog to scale back heavy features under load? One plus side is that we'd get immediate CPU percentages here instead of waiting it to kick in with WebSockets
cpustr := unknown
var cpuColour string
lessThanSwitch := func(number, lowerBound, midBound int) string {
switch {
case number < lowerBound:
return "stat_green"
case number < midBound:
return "stat_orange"
}
return "stat_red"
}
var ramstr, ramColour string
memres, err := mem.VirtualMemory()
if err != nil {
ramstr = unknown
} else {
totalCount, totalUnit := c.ConvertByteUnit(float64(memres.Total))
usedCount := c.ConvertByteInUnit(float64(memres.Total-memres.Available), totalUnit)
// Round totals with .9s up, it's how most people see it anyway. Floats are notoriously imprecise, so do it off 0.85
var totstr string
if (totalCount - float64(int(totalCount))) > 0.85 {
usedCount += 1.0 - (totalCount - float64(int(totalCount)))
totstr = strconv.Itoa(int(totalCount) + 1)
} else {
totstr = fmt.Sprintf("%.1f", totalCount)
}
if usedCount > totalCount {
usedCount = totalCount
}
ramstr = fmt.Sprintf("%.1f", usedCount) + " / " + totstr + totalUnit
ramperc := ((memres.Total - memres.Available) * 100) / memres.Total
ramColour = lessThanSwitch(int(ramperc), 50, 75)
}
var m runtime.MemStats
runtime.ReadMemStats(&m)
memCount, memUnit := c.ConvertByteUnit(float64(m.Sys))
greaterThanSwitch := func(number, lowerBound, midBound int) string {
switch {
case number > midBound:
return "stat_green"
case number > lowerBound:
return "stat_orange"
}
return "stat_red"
}
// TODO: Add a stat store for this?
var intErr error
extractStat := func(stmt *sql.Stmt, args ...interface{}) (stat int) {
err := stmt.QueryRow(args...).Scan(&stat)
if err != nil && err != sql.ErrNoRows {
intErr = err
}
return stat
}
var stmts dashStmts
switch qgen.Builder.GetAdapter().GetName() {
case "mysql":
stmts, err = dashMySQLStmts()
case "mssql":
stmts, err = dashMSSQLStmts()
default:
return c.InternalError(errors.New("Unknown database adapter on dashboard"), w, r)
}
if err != nil {
return c.InternalError(err, w, r)
}
// TODO: Allow for more complex phrase structures than just suffixes
postCount := extractStat(stmts.todaysPostCount)
postInterval := p.GetTmplPhrase("panel_dashboard_day_suffix")
postColour := greaterThanSwitch(postCount, 5, 25)
topicCount := extractStat(stmts.todaysTopicCount)
topicInterval := p.GetTmplPhrase("panel_dashboard_day_suffix")
topicColour := greaterThanSwitch(topicCount, 0, 8)
reportCount := extractStat(stmts.weeklyTopicCountByForum, c.ReportForumID)
reportInterval := p.GetTmplPhrase("panel_dashboard_week_suffix")
newUserCount := extractStat(stmts.todaysNewUserCount)
newUserInterval := p.GetTmplPhrase("panel_dashboard_week_suffix")
// Did any of the extractStats fail?
if intErr != nil {
return c.InternalError(intErr, w, r)
}
grid1 := []GE{}
addElem1 := func(id, href, body string, order int, class, back, textColour, tooltip string) {
grid1 = append(grid1, GE{id, href, body, order, class, back, textColour, tooltip})
}
gridElements := []GE{}
addElem := func(id, href, body string, order int, class, back, textColour, tooltip string) {
gridElements = append(gridElements, GE{id, href, body, order, class, back, textColour, tooltip})
}
// TODO: Implement a check for new versions of Gosora
// TODO: Localise this
//addElem1("dash-version", "", "v" + version.String(), 0, "grid_istat stat_green", "", "", "Gosora is up-to-date :)")
addElem1("dash-version", "", "v"+c.SoftwareVersion.String(), 0, "grid_istat", "", "", "")
addElem1("dash-cpu", "", p.GetTmplPhrasef("panel_dashboard_cpu", cpustr), 1, "grid_istat "+cpuColour, "", "", p.GetTmplPhrase("panel_dashboard_cpu_desc"))
addElem1("dash-ram", "", p.GetTmplPhrasef("panel_dashboard_ram", ramstr), 2, "grid_istat "+ramColour, "", "", p.GetTmplPhrase("panel_dashboard_ram_desc"))
addElem1("dash-memused", "/panel/analytics/memory/", p.GetTmplPhrasef("panel_dashboard_memused", memCount, memUnit), 2, "grid_istat", "", "", p.GetTmplPhrase("panel_dashboard_memused_desc"))
/*dirSize := getDirSize()
if dirSize.Size != 0 {
dirFloat, unit := c.ConvertByteUnit(float64(dirSize.Size))
addElem1("dash-disk","", p.GetTmplPhrasef("panel_dashboard_disk", dirFloat, unit), 2, "grid_istat", "", "", p.GetTmplPhrase("panel_dashboard_disk_desc"))
dur := time.Since(dirSize.Time)
if dur.Seconds() > 3 {
startDirSizeTask()
}
} else {
addElem1("dash-disk","", p.GetTmplPhrase("panel_dashboard_disk_unknown"), 2, "grid_istat", "", "", p.GetTmplPhrase("panel_dashboard_disk_desc"))
startDirSizeTask()
}*/
if c.EnableWebsockets {
uonline := c.WsHub.UserCount()
gonline := c.WsHub.GuestCount()
totonline := uonline + gonline
//reqCount := 0
onlineColour := greaterThanSwitch(totonline, 3, 10)
onlineGuestsColour := greaterThanSwitch(gonline, 1, 10)
onlineUsersColour := greaterThanSwitch(uonline, 1, 5)
totonline, totunit := c.ConvertFriendlyUnit(totonline)
uonline, uunit := c.ConvertFriendlyUnit(uonline)
gonline, gunit := c.ConvertFriendlyUnit(gonline)
addElem("dash-totonline", "", p.GetTmplPhrasef("panel_dashboard_online", totonline, totunit), 3, "grid_stat "+onlineColour, "", "", p.GetTmplPhrase("panel_dashboard_online_desc"))
addElem("dash-gonline", "", p.GetTmplPhrasef("panel_dashboard_guests_online", gonline, gunit), 4, "grid_stat "+onlineGuestsColour, "", "", p.GetTmplPhrase("panel_dashboard_guests_online_desc"))
addElem("dash-uonline", "", p.GetTmplPhrasef("panel_dashboard_users_online", uonline, uunit), 5, "grid_stat "+onlineUsersColour, "", "", p.GetTmplPhrase("panel_dashboard_users_online_desc"))
//addElem("dash-reqs","", strconv.Itoa(reqCount) + " reqs / second", 7, "grid_stat grid_end_group " + topicColour, "", "", "The number of requests over the last 24 hours")
}
addElem("dash-postsperday", "", p.GetTmplPhrasef("panel_dashboard_posts", postCount, postInterval), 6, "grid_stat "+postColour, "", "", p.GetTmplPhrase("panel_dashboard_posts_desc"))
addElem("dash-topicsperday", "", p.GetTmplPhrasef("panel_dashboard_topics", topicCount, topicInterval), 7, "grid_stat "+topicColour, "", "", p.GetTmplPhrase("panel_dashboard_topics_desc"))
addElem("dash-totonlineperday", "", p.GetTmplPhrasef("panel_dashboard_online_day"), 8, "grid_stat stat_disabled", "", "", p.GetTmplPhrase("panel_dashboard_coming_soon") /*, "The people online over the last 24 hours"*/)
addElem("dash-searches", "", p.GetTmplPhrasef("panel_dashboard_searches_day"), 9, "grid_stat stat_disabled", "", "", p.GetTmplPhrase("panel_dashboard_coming_soon") /*"The number of searches over the last 7 days"*/)
addElem("dash-newusers", "", p.GetTmplPhrasef("panel_dashboard_new_users", newUserCount, newUserInterval), 10, "grid_stat", "", "", p.GetTmplPhrasef("panel_dashboard_new_users_desc"))
addElem("dash-reports", "", p.GetTmplPhrasef("panel_dashboard_reports", reportCount, reportInterval), 11, "grid_stat", "", "", p.GetTmplPhrasef("panel_dashboard_reports_desc"))
if false {
addElem("dash-minperuser", "", "?? minutes / user / week", 12, "grid_stat stat_disabled", "", "", p.GetTmplPhrase("panel_dashboard_coming_soon") /*"The average number of number of minutes spent by each active user over the last 7 days"*/)
addElem("dash-visitorsperweek", "", "?? visitors / week", 13, "grid_stat stat_disabled", "", "", p.GetTmplPhrase("panel_dashboard_coming_soon") /*"The number of unique visitors we've had over the last 7 days"*/)
addElem("dash-postsperuser", "", "?? posts / user / week", 14, "grid_stat stat_disabled", "", "", p.GetTmplPhrase("panel_dashboard_coming_soon") /*"The average number of posts made by each active user over the past week"*/)
}
return renderTemplate("panel", w, r, basePage.Header, c.Panel{basePage, "panel_dashboard_right", "", "panel_dashboard", c.DashGrids{grid1, gridElements}})
}
type dirSize struct {
Size int
Time time.Time
}
func init() {
cachedDirSize.Store(dirSize{0, time.Now()})
}
var cachedDirSize atomic.Value
var dstMu sync.Mutex
var dstMuGuess = 0
func startDirSizeTask() {
if dstMuGuess == 1 {
return
}
dstMu.Lock()
dstMuGuess = 1
go func() {
defer func() {
dstMuGuess = 0
dstMu.Unlock()
}()
defer c.EatPanics()
dDirSize, e := c.DirSize(".")
if e != nil {
c.LogWarning(e)
}
cachedDirSize.Store(dirSize{dDirSize, time.Now()})
}()
}
func getDirSize() dirSize {
return cachedDirSize.Load().(dirSize)
}
type StatsDiskJson struct {
Total string `json:"total"`
}
func StatsDisk(w http.ResponseWriter, r *http.Request, user *c.User) c.RouteError {
dirSize := getDirSize()
dirFloat, unit := c.ConvertByteUnit(float64(dirSize.Size))
u := p.GetTmplPhrasef("unit", dirFloat, unit)
oBytes, err := json.Marshal(StatsDiskJson{u})
if err != nil {
return c.InternalErrorJS(err, w, r)
}
w.Write(oBytes)
return nil
}