-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.go
82 lines (76 loc) · 1.82 KB
/
application.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
package main
import (
"context"
"crypto/tls"
"net/http"
"os"
"sync"
"time"
"github.com/qiniu/log"
)
type Scheduler struct {
ctx context.Context
cancel context.CancelFunc
wg *sync.WaitGroup
cfg *AppConfig
closeOnce sync.Once
}
func (scheduler *Scheduler) Ready() {
scheduler.wg.Add(1)
}
func (scheduler *Scheduler) Ack() {
scheduler.wg.Done()
}
func NewScheduler(cfg *AppConfig) (*Scheduler, error) {
ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
return &Scheduler{cfg: cfg, ctx: ctx, cancel: cancel, wg: wg}, nil
}
func (scheduler *Scheduler) Run() error {
cfg := scheduler.cfg
tm, err := newMaker(cfg.Input, cfg.Port, scheduler.cfg.Go, scheduler.ctx)
if err != nil {
return err
}
file, err := os.Create(scheduler.cfg.Output)
if err != nil {
log.Warn("failed to create output file ", err)
return err
}
defer file.Close()
saver := newTextSaver(file, cfg.Go)
defer saver.Close()
defer scheduler.wg.Wait()
defer tm.Close()
scheduler.makeHttpClient()
go saver.Run()
return tm.Run(scheduler.startGo(tm, saver))
}
func (scheduler *Scheduler) makeHttpClient() *http.Client {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
}
client := &http.Client{Transport: transport, Timeout: time.Duration(scheduler.cfg.TTL)}
return client
}
func (scheduler *Scheduler) startGo(tm *taskMaker, saver Saver) func() {
var i uint
return func() {
if i >= scheduler.cfg.Go {
return
}
i += 1
log.Debug("start goroutine", i)
s := NewScanner(tm.channel(), saver, http.DefaultClient, scheduler)
scheduler.Ready()
go s.Run()
}
}
func (scheduler *Scheduler) Close() {
scheduler.closeOnce.Do(scheduler.close)
}
func (scheduler *Scheduler) close() {
log.Info("scheduler exit ...")
scheduler.cancel()
}