/
precache.go
377 lines (334 loc) · 9.28 KB
/
precache.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
373
374
375
376
377
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name : precache.go
* Purpose :
* Creation Date : 03-19-2014
* Last Modified : Wed 28 May 2014 12:31:47 AM UTC
* Created By : Kiyor
_._._._._._._._._._._._._._._._._._._._._.*/
package main
import (
"crypto/md5"
"encoding/base64"
"flag"
"fmt"
"github.com/dustin/go-humanize"
"github.com/kiyor/gfind/lib"
"github.com/vaughan0/go-ini"
"github.com/wsxiaoys/terminal/color"
"io"
"net"
"net/http"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type client struct {
c *http.Client
loc *bool
}
func (c *client) lock() {
*c.loc = true
}
func (c *client) unlock() {
*c.loc = false
}
type worker struct {
sync.WaitGroup
counter *int
}
func (w *worker) add(n int) {
w.Add(n)
*w.counter += n
}
func (w *worker) done() {
*w.counter--
w.Done()
}
func initClient() client {
c := &http.Client{Transport: &transport}
return client{c, new(bool)}
}
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
func getClient(clients []client) int {
for {
for k, c := range clients {
if !*c.loc {
c.lock()
return k
}
}
time.Sleep(1 * time.Millisecond)
}
}
var (
fhosts *string = flag.String("hosts", "server.com", "http hostname")
fvhost *string = flag.String("vhost", "client.com", "vhost hostname")
do *bool = flag.Bool("do", false, "do request")
fproc *int = flag.Int("proc", 0, "worker")
conff *string = flag.String("f", "conf.ini", "conf file location")
purge *bool = flag.Bool("purgefirst", false, "do purge request before anything")
ngxSecurityLink *string = flag.String("ngxsecuritylink", "", "Nginx Security Link security key")
cStatus *string = flag.String("cachestatus", "X-Cache", "Nginx Upstream status Header")
timeOut *string = flag.String("timeout", "0s", "request timeout, default will overwrite to 3s")
verbose *bool = flag.Bool("v", false, "verbose")
rootdir, vhost, security, cacheStatus string
hosts, httphosts []string
proc int
timeout time.Duration
clients []client
transport = http.Transport{
Dial: dialTimeout,
}
)
func readConff() {
f, err := ini.LoadFile(*conff)
chkErr(err)
hs, _ := f.Get("precache", "hosts")
hosts = strings.Split(hs, " ")
vhost, _ = f.Get("precache", "vhost")
security, _ = f.Get("precache", "security")
cacheStatus, _ = f.Get("precache", "cachestatus")
tiout, ok := f.Get("precache", "timeout")
if !ok {
timeout = 3 * time.Second
} else {
timeout, err = time.ParseDuration(tiout)
chkErr(err)
}
p, ok := f.Get("precache", "proc")
if !ok {
p = "2"
}
if p != "" {
proc, err = strconv.Atoi(p)
if err != nil {
fmt.Println("proc should be number")
}
}
if *fhosts != "server.com" {
hosts = strings.Split(*fhosts, " ")
}
if *fvhost != "client.com" {
vhost = *fvhost
}
if *ngxSecurityLink != "" {
security = *ngxSecurityLink
}
if *timeOut != "0s" {
timeout, err = time.ParseDuration(*timeOut)
chkErr(err)
}
if *cStatus != "X-Cache" {
cacheStatus = *cStatus
} else if cacheStatus == "" {
cacheStatus = "X-Cache"
}
if ok && *fproc == 0 {
} else if *fproc == 0 {
proc = 2
} else {
proc = *fproc
}
}
func init() {
flag.Parse()
runtime.GOMAXPROCS(runtime.NumCPU())
readConff()
for i := 0; i < proc; i++ {
clients = append(clients, initClient())
}
for _, host := range hosts {
host = "http://" + host
httphosts = append(httphosts, host)
}
}
func time2fmt(t time.Time) string {
return t.Format("Mon, 02 Jan 2006 15:04:05 GMT")
}
func timespec2time(t syscall.Timespec) time.Time {
return time.Unix(t.Sec, t.Nsec)
}
func main() {
conf := gfind.InitFindConfByIni(*conff)
fs := gfind.Find(conf)
if *do {
var wg sync.WaitGroup
for _, h := range httphosts {
wg.Add(1)
go Gourl(h, fs, &wg)
}
wg.Wait()
} else {
gfind.Output(fs, *verbose)
}
}
func Gourl(host string, fs []gfind.File, wg *sync.WaitGroup) {
var w worker
w.counter = new(int)
for k, v := range fs {
w.add(1)
id := getClient(clients)
go func(id int, v gfind.File, w *worker, k int) {
clients[id].gogogo(host, v, k, id)
w.done()
}(id, v, &w, k)
}
w.Wait()
wg.Done()
}
func (c *client) purge(host string, f gfind.File, k int, id int) {
var Url *url.URL
Url, err := url.Parse(host)
chkErr(err)
Url.Path += "/purge"
Url.Path += f.Relpath
var u string
u = Url.String()
if security != "" {
u += "?" + ParseNgxSecurityLink(security, host, f)
}
req, err := http.NewRequest("HEAD", u, nil)
req.Close = true
if vhost != "client.com" {
req.Host = vhost
}
resp, err := c.c.Do(req)
chkErr(err)
if resp.StatusCode == 200 {
color.Printf("%6v-%-2d @{g}%-17v@{|} %v %v\n", k, id, "PURGE:SUCCESS", Url.String(), f.Size())
} else if resp.StatusCode == 404 {
color.Printf("%6v-%-2d @{y}%-17v@{|} %v %v\n", k, id, "PURGE:NOFILE", Url.String(), f.Size())
}
}
func ParseNgxSecurityLink(key string, host string, f gfind.File) string {
var Url *url.URL
Url, err := url.Parse(host)
chkErr(err)
Url.Path += f.Relpath
loc := Url.String()[len(host):]
token := key + loc + "9999999999"
h := md5.New()
io.WriteString(h, token)
str := base64.StdEncoding.EncodeToString(h.Sum(nil))
r := strings.NewReplacer("/", "_", "=", "", "+", "-")
return "st=" + r.Replace(str) + "&e=9999999999"
}
// this is just a single file precache
func (c *client) gogogo(host string, f gfind.File, k int, id int) {
if *purge {
c.purge(host, f, k, id)
}
var Url *url.URL
Url, err := url.Parse(host)
chkErr(err)
Url.Path += f.Relpath
var u string
u = Url.String()
if security != "" {
u += "?" + ParseNgxSecurityLink(security, host, f)
}
color.Printf("%6v-%-2d @{y}%-17v@{|} %v %v\n", k, id, "START", Url.String(), f.Size())
req, err := http.NewRequest("HEAD", u, nil)
req.Close = true
if vhost != "client.com" {
req.Host = vhost
}
for true {
resp, err := c.c.Do(req)
if err != nil {
color.Printf("@{g}%v\n", err.Error())
time.Sleep(5 * time.Second)
continue
}
defer resp.Body.Close()
// if http resp is not 200, that's means have some err, then skip this file.
if resp.StatusCode != 200 {
color.Printf("@{g}%6v-%-2d %v %v %v\n", k, id, Url.String(), "StatusCode", resp.StatusCode)
// normally it shouldn't be 404, if it is, then means path is not correct. stop do loop
if resp.StatusCode == 404 {
break
}
// other wise, wait 5s for user consider, then start from beginning
time.Sleep(5 * time.Second)
continue
}
var b1, b2, b3 bool
// if it has cache status header, then
if val, ok := resp.Header[cacheStatus]; ok {
// if cache status is HIT, then everthing is expected
if val[0] == "HIT" {
b1 = true
// if it is doing updating or it is miss
} else if val[0] == "UPDATING" || val[0] == "MISS" {
// set sleep time depends on file size then start from beginning
t, err := time.ParseDuration(fmt.Sprintf("%dms", f.Size()/100000))
chkErr(err)
if *verbose {
color.Printf("%6v-%-2d @{r}%7s:%-9s@{|} %v Size:%v SLEEP:%vms\n", k, id, cacheStatus, val[0], Url.String(), humanize.IBytes(uint64(f.Size())), f.Size()/100000)
}
time.Sleep(t)
continue
} else {
// if not HIT/UPDATING/MISS then print result and seep 2s, start from beginning
if *verbose {
color.Printf("%6v-%-2d @{r}%7s:%-9s@{|} %v Size:%v SLEEP\n", k, id, cacheStatus, val[0], Url.String(), humanize.IBytes(uint64(f.Size())))
}
time.Sleep(2 * time.Second)
continue
}
} else { // if has no cache status header, then means missing setup, output debug information and start from beginning
if *verbose {
color.Printf("%6v-%-2d @{r}%7s:%-9v@{|} %v SLEEP\n", k, id, cacheStatus, "NULL", Url.String())
}
time.Sleep(5 * time.Second)
continue
}
// if header has "Last-Modified" which it should have by default.
if val, ok := resp.Header["Last-Modified"]; ok {
// if time match on orginal server then it is good
if val[0] == time2fmt(timespec2time(f.Stat.Mtim)) {
b2 = true
} else { // else means file need recache, then purge and redo this file from beginning
color.Printf("@{b}%6v-%-2d %v %v %v %v %v\n", k, id, Url.String(), " Header: ", val[0], " File: ", time2fmt(timespec2time(f.Stat.Mtim)))
c.purge(host, f, k, id)
continue
}
} else {
color.Printf("@{g}%6v-%-2d %-17v %v %v\n", k, id, "NO:Last-Modified", Url.String())
}
// if header has "Content-Length" which it should have by default
if val, ok := resp.Header["Content-Length"]; ok {
s, _ := strconv.Atoi(val[0])
// if size match on orginal server then it is good
if int64(s) == f.Size() {
b3 = true
} else { // else means file need recache, then purge and redo this file from beginning
color.Printf("@{b}%6v-%-2d %v %v %v %v %v\n", k, id, Url.String(), " Header: ", val[0], " File: ", f.Size())
c.purge(host, f, k, id)
continue
}
} else {
color.Printf("@{g}%6v-%-2d %-17v %v %v\n", k, id, "NO:Content-Length", Url.String())
}
// if cache hit, size and last mod match, then break loop
if b1 && b2 && b3 {
if *verbose {
color.Printf("%6v-%-2d @{g}%-17v@{|} %v %v\n", k, id, "FINISH", Url.String(), f.Size())
}
break
}
time.Sleep(5000 * time.Millisecond)
}
c.unlock()
}
func chkErr(err error) {
if err != nil {
fmt.Println(err.Error())
}
}