-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
305 lines (276 loc) · 6.3 KB
/
main.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
package main
import (
"crypto/md5"
"embed"
"fmt"
"io"
"io/fs"
"io/ioutil"
"log"
"mime"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"sync"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
cr "github.com/muzea/concurrency"
"github.com/muzea/counter"
)
type benchInfo struct {
url string
user_id string
password string
total string
concurrency string
problem_id string
answer string
}
type wsData struct {
Action string `json:"action"`
ID string `json:"id"`
Payload map[string]string `json:"payload"`
}
type benchResult struct {
ID string `json:"id"`
Stage string `json:"stage"`
Count200 int `json:"count200"`
Count50x int `json:"count50x"`
CountUnknown int `json:"countUnknown"`
Timecost int `json:"timecost"`
}
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleBench(ws *websocket.Conn, data wsData) {
var bi = benchInfo{
url: data.Payload["url"],
user_id: data.Payload["user_id"],
password: data.Payload["password"],
total: data.Payload["total"],
concurrency: data.Payload["concurrency"],
problem_id: data.Payload["problem_id"],
answer: data.Payload["answer"],
}
var err error
err = ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
}{
ID: data.ID,
Stage: "pong",
})
if err != nil {
log.Println("error write json: " + err.Error())
}
cookieJar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: cookieJar,
}
h := md5.New()
io.WriteString(h, bi.password)
client.PostForm(bi.url+"login.php", url.Values{
"user_id": {bi.user_id},
"password": {fmt.Sprintf("%x", h.Sum(nil))},
})
err = ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
}{
ID: data.ID,
Stage: "login_check",
})
if err != nil {
log.Println("error write json: " + err.Error())
}
submitURL := bi.url + "submit.php"
r, _ := regexp.Compile("^\\d+$")
resp, err := client.PostForm(submitURL, url.Values{
"id": {bi.problem_id},
"language": {"0"},
"source": {bi.answer},
})
if err != nil {
ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
Error string `json:"error"`
}{
ID: data.ID,
Stage: "check_mode",
Error: fmt.Sprintln(err),
})
return
}
if resp.StatusCode != http.StatusOK {
ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
Error string `json:"error"`
}{
ID: data.ID,
Stage: "check_mode",
Error: "response status code error " + string(resp.StatusCode),
})
return
}
body, _ := ioutil.ReadAll(resp.Body)
if !r.MatchString(string(body[:])) {
ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
Error string `json:"error"`
}{
ID: data.ID,
Stage: "check_mode",
Error: "response body not match " + string(body[:]),
})
return
}
ws.WriteJSON(struct {
ID string `json:"id"`
Stage string `json:"stage"`
}{
ID: data.ID,
Stage: "benching",
})
start := time.Now()
concurrency, err := strconv.Atoi(bi.concurrency)
total, err := strconv.Atoi(bi.total)
count50x := counter.NewCounter(0, total)
count200 := counter.NewCounter(0, total)
countUnknown := counter.NewCounter(0, total)
var l sync.Mutex
var updateBenchResult = func(stage string) {
elapsed := time.Since(start).Milliseconds()
var nextData benchResult = benchResult{
Stage: stage,
ID: data.ID,
Count200: count200.Value(),
Count50x: count50x.Value(),
CountUnknown: countUnknown.Value(),
Timecost: int(elapsed),
}
l.Lock()
ws.WriteJSON(nextData)
l.Unlock()
}
cr.Run(func(runIndex int) {
resp, err := client.PostForm(submitURL, url.Values{
"id": {bi.problem_id},
"language": {"0"},
"source": {bi.answer},
})
if err != nil {
fmt.Println(err)
countUnknown.Plus(1)
go updateBenchResult("bench_update")
return
}
if resp.StatusCode >= 500 && resp.StatusCode <= 599 {
count50x.Plus(1)
go updateBenchResult("bench_update")
return
}
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == http.StatusOK {
if r.MatchString(string(body[:])) {
count200.Plus(1)
go updateBenchResult("bench_update")
return
}
}
countUnknown.Plus(1)
// fmt.Println("dump resp ", runIndex)
// fmt.Println("[", string(body[:]), "]")
go updateBenchResult("bench_update")
return
}, concurrency, total)
elapsed := time.Since(start)
fmt.Printf("total cost -> %dms\n", elapsed/time.Millisecond)
count50x.Flush()
count200.Flush()
countUnknown.Flush()
updateBenchResult("bench_end")
}
func jsonApi(c *gin.Context) {
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println("error get connection")
log.Fatal(err)
}
defer ws.Close()
var data wsData
for {
err = ws.ReadJSON(&data)
if err != nil {
var wsClose = "websocket: close 1001 (going away)"
if err.Error() == wsClose {
return
} else {
log.Println("error read json")
log.Fatal(err.Error())
}
}
if data.Action == "start_bench" {
// log.Println("recive data ", data)
handleBench(ws, data)
}
}
}
//go:embed build/public/*
var staticFS embed.FS
type embedFileSystem struct {
http.FileSystem
indexes bool
}
func (e embedFileSystem) Exists(prefix string, path string) bool {
f, err := e.Open(path)
if err != nil {
return false
}
s, _ := f.Stat()
if s.IsDir() && !e.indexes {
return false
}
return true
}
func EmbedFolder(fsEmbed embed.FS, targetPath string, index bool) static.ServeFileSystem {
subFS, err := fs.Sub(fsEmbed, targetPath)
if err != nil {
panic(err)
}
return embedFileSystem{
FileSystem: http.FS(subFS),
indexes: index,
}
}
func websocketGin() {
r := gin.Default()
r.Use(cors.Default())
r.GET("/ws", jsonApi)
fs := EmbedFolder(staticFS, "build/public", true)
r.Use(static.Serve("/", fs))
r.NoRoute(func(c *gin.Context) {
c.File("./public/index.html")
})
r.Run(":8000")
}
func mustFS() http.FileSystem {
sub, err := fs.Sub(staticFS, "build/public")
if err != nil {
panic(err)
}
return http.FS(sub)
}
func main() {
mime.AddExtensionType(".js", "application/javascript")
websocketGin()
}