/
run.go
122 lines (107 loc) · 2.26 KB
/
run.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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/sirupsen/logrus"
"github.com/wrfly/gus-proxy/config"
"github.com/wrfly/gus-proxy/db"
"github.com/wrfly/gus-proxy/gus"
)
func runGus(conf *config.Config) error {
if conf.Debug {
logrus.SetLevel(logrus.DebugLevel)
}
logrus.Info("starting gus-proxy")
if err := conf.Validate(); err != nil {
logrus.Fatalf("bad config error: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
// update proxy status
readyChan := make(chan interface{})
wg.Add(1)
go func() {
defer wg.Done()
logrus.Info("updating proxies")
conf.UpdateProxies()
readyChan <- true
close(readyChan)
tk := time.NewTicker(time.Second * time.Duration(conf.ProxyUpdateInterval))
defer tk.Stop()
for {
select {
case <-ctx.Done():
return
case <-tk.C:
conf.UpdateProxies()
}
}
}()
<-readyChan
// handle signals
logrus.Debug("handle sigs")
sigStop := make(chan os.Signal)
signal.Notify(sigStop, syscall.SIGINT, syscall.SIGTERM)
sigKill := make(chan os.Signal)
signal.Notify(sigKill, os.Kill)
// init db
logrus.Debug("init dns db")
dnsDB, err := db.New(conf.DBFilePath)
if err != nil {
logrus.Fatal(err)
}
defer dnsDB.Close()
go func() {
if !conf.Debug {
return
}
addr := fmt.Sprintf(":%s", conf.DebugPort)
logrus.Infof("debug is serving on %s", addr)
http.ListenAndServe(addr, nil)
}()
srv := http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", conf.ListenPort),
Handler: gus.New(conf, dnsDB),
}
go func() {
wg.Add(1)
defer wg.Done()
logrus.Infof("serving on %s", srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Error(err)
}
}()
select {
case <-sigStop:
logrus.Info("about to stop")
cancel()
srvCtx, srvCancel := context.WithTimeout(context.Background(), time.Second*3)
defer srvCancel()
srv.Shutdown(srvCtx)
quit := make(chan struct{})
go func() {
wg.Wait()
quit <- struct{}{}
}()
defer close(quit)
select {
case <-sigStop:
srvCancel()
logrus.Warn("force quit!")
case <-quit:
logrus.Info("quit")
}
case <-sigKill:
cancel()
srv.Close()
}
logrus.Info("gus-proxy stopped")
return nil
}