-
Notifications
You must be signed in to change notification settings - Fork 16
/
web.go
372 lines (306 loc) · 7.8 KB
/
web.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package main
import (
"database/sql"
"flag"
"html/template"
"log"
"net"
"net/http"
"os/exec"
"strconv"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"github.com/pkg/errors"
)
var (
databaseDSN = flag.String("database-dsn", "root:root@/isu6fportal", "database `dsn`")
debugMode = flag.Bool("debug", false, "enable debug mode")
)
var db *sql.DB
var templates = map[string]*template.Template{}
var sessionStore sessions.Store
var locJST *time.Location
const (
sessionName = "isu6f"
sessionKeyTeamID = "team-id"
)
func parseTemplateAsset(t *template.Template, name string) error {
content, err := Asset(name)
if err != nil {
return err
}
_, err = t.Parse(string(content))
return err
}
func initWeb() error {
var err error
dsn := *databaseDSN + "?charset=utf8mb4&parseTime=true&loc=Asia%2FTokyo&time_zone='Asia%2FTokyo'"
db, err = sql.Open("mysql", dsn)
if err != nil {
return errors.Wrapf(err, "sql.Open %q", dsn)
}
err = db.Ping()
if err != nil {
return errors.Wrapf(err, "db.Ping %q", dsn)
}
const templatesRoot = "views/"
for _, file := range []string{
"index.tmpl", "login.tmpl", "debug-queue.tmpl", "debug-leaderboard.tmpl", "debug-proxies.tmpl", "messages.tmpl",
} {
t := template.New(file).Funcs(template.FuncMap{
"contestEnded": func() bool {
return getContestStatus() == contestStatusEnded
},
"plusOne": func(i int) int {
return i + 1
},
})
if err := parseTemplateAsset(t, templatesRoot+"layout.tmpl"); err != nil {
return err
}
if err := parseTemplateAsset(t, templatesRoot+file); err != nil {
return err
}
templates[file] = t
}
locJST, err = time.LoadLocation("Asia/Tokyo")
if err != nil {
return err
}
sessionStore = sessions.NewCookieStore([]byte(":beers:"))
return nil
}
type Team struct {
ID int
Name string
IPAddr string
InstanceName string
}
func loadTeam(id uint64) (*Team, error) {
var team Team
row := db.QueryRow("SELECT id,name,IFNULL(ip_address, ''),IFNULL(instance_name, '') FROM teams WHERE id = ?", id)
err := row.Scan(&team.ID, &team.Name, &team.IPAddr, &team.InstanceName)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &team, err
}
func loadTeamFromSession(req *http.Request) (*Team, error) {
if *debugMode {
c, _ := req.Cookie("debug_team")
if c != nil {
n, _ := strconv.ParseUint(c.Value, 10, 0)
if n != 0 {
return loadTeam(n)
}
}
}
sess, err := sessionStore.New(req, sessionName)
if err != nil {
if cerr, ok := err.(securecookie.Error); ok && cerr.IsDecode() {
// 違う session secret でアクセスしにくるとこれなので無視
} else {
return nil, errors.Wrap(err, "sessionStore.New()")
}
}
v, ok := sess.Values[sessionKeyTeamID]
if !ok {
return nil, nil
}
teamID, ok := v.(uint64)
if !ok {
return nil, nil
}
team, err := loadTeam(teamID)
return team, errors.Wrapf(err, "loadTeam(id=%#v)", teamID)
}
type viewParamsLayout struct {
Team *Team
}
func serveIndex(w http.ResponseWriter, req *http.Request) error {
return serveIndexWithMessage(w, req, "")
}
func serveIndexWithMessage(w http.ResponseWriter, req *http.Request, message string) error {
team, err := loadTeamFromSession(req)
if err != nil {
return err
}
teamID := 0
if team != nil {
teamID = team.ID
}
plotLines, latestScores, err := getResults(db, teamID, 10, getRankingFixedAt())
if err != nil {
return err
}
teamResults, err := getTeamResults(db, teamID)
if err != nil {
return err
}
// キューをゲット
jobs, err := getQueuedJobs(db)
if err != nil {
return err
}
messages, err := getMessages()
if err != nil {
return err
}
if message != "" {
messages = append(messages, Message{Message: message, Kind: "danger"})
}
return templates["index.tmpl"].Execute(
w, struct {
viewParamsLayout
PlotLines []PlotLine
LatestScores []LatestScore
IsRankingFixed bool
TeamResults []TeamResult
Jobs []QueuedJob
Messages []Message
}{
viewParamsLayout{team},
plotLines,
latestScores,
getRankingFixedAt().Before(time.Now()),
teamResults,
jobs,
messages,
},
)
}
type viewParamsLogin struct {
viewParamsLayout
ErrorMessage string
}
func serveLogin(w http.ResponseWriter, req *http.Request) error {
if getContestStatus() == contestStatusEnded {
http.Error(w, "Today's final has ended", http.StatusForbidden)
return nil
}
team, err := loadTeamFromSession(req)
if err != nil {
return err
}
if req.Method == "GET" {
return templates["login.tmpl"].Execute(
w, viewParamsLogin{viewParamsLayout{team}, ""})
}
var (
id = req.FormValue("team_id")
password = req.FormValue("password")
)
var teamID uint64
row := db.QueryRow("SELECT id FROM teams WHERE id = ? AND password = ? LIMIT 1", id, password)
err = row.Scan(&teamID)
if err != nil {
if err == sql.ErrNoRows {
return templates["login.tmpl"].Execute(
w, viewParamsLogin{viewParamsLayout{team}, "Wrong id/password pair"})
} else {
return err
}
}
sess, err := sessionStore.New(req, sessionName)
if err != nil {
if cerr, ok := err.(securecookie.Error); ok && cerr.IsDecode() {
// 違う session secret でアクセスしにくるとこれなので無視
} else {
return errors.Wrap(err, "sessionStore.New()")
}
}
sess.Values[sessionKeyTeamID] = teamID
err = sess.Save(req, w)
if err != nil {
return err
}
http.Redirect(w, req, "/", 302)
return nil
}
type httpError interface {
httpStatus() int
error
}
type errHTTP int
func (s errHTTP) Error() string { return http.StatusText(int(s)) }
func (s errHTTP) httpStatus() int { return int(s) }
type errHTTPMessage struct {
status int
message string
}
func (m errHTTPMessage) Error() string { return m.message }
func (m errHTTPMessage) httpStatus() int { return m.status }
func serveStatic(w http.ResponseWriter, req *http.Request) error {
path := req.URL.Path[1:]
content, err := Asset(path)
if err != nil {
return errHTTP(http.StatusNotFound)
}
if strings.HasSuffix(path, ".css") {
w.Header().Set("Content-Type", "text/css")
}
w.Write(content)
return nil
}
func serveUpdateTeam(w http.ResponseWriter, req *http.Request) error {
if getContestStatus() == contestStatusEnded {
http.Error(w, "Today's final has ended", http.StatusForbidden)
return nil
}
if req.Method != http.MethodPost {
return errHTTP(http.StatusMethodNotAllowed)
}
team, err := loadTeamFromSession(req)
if err != nil {
return err
}
if team == nil {
return errHTTP(http.StatusForbidden)
}
instanceName := req.FormValue("instance_name")
ipAddress := req.FormValue("ip_address")
if ipAddress != "" {
ip := net.ParseIP(ipAddress)
if ip == nil || ip.To4() == nil {
return errHTTP(http.StatusBadRequest)
}
}
_, err = db.Exec("UPDATE teams SET instance_name = ?, ip_address = ? WHERE id = ?", instanceName, ipAddress, team.ID)
if err != nil {
return err
}
// proxyにチームのIPアドレスを通知する
err = exec.Command(`/usr/local/bin/consul`, `event`, `-name`, `nginx_reload`, `-node`, `proxy`).Run()
if err != nil {
log.Printf("consul: %v", err)
return err
}
// IPアドレスの反映に時間がかかることを考えてこのへんで3秒待つ
time.Sleep(3 * time.Second)
http.Redirect(w, req, "/", http.StatusFound)
return nil
}
func serveDebugLeaderboard(w http.ResponseWriter, req *http.Request) error {
plotLines, latestScores, err := getResults(db, 0, 26, time.Now()) // ここは常に最新のを使う
if err != nil {
return err
}
type viewParamsDebugLeaderboard struct {
viewParamsLayout
PlotLines []PlotLine
LatestScores []LatestScore
}
return templates["debug-leaderboard.tmpl"].Execute(
w, viewParamsDebugLeaderboard{
viewParamsLayout{nil},
plotLines,
latestScores,
},
)
}