-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
115 lines (98 loc) · 2.39 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
package main
import (
"context"
"log"
"net"
"time"
flag "github.com/spf13/pflag"
"github.com/ftl/rigproxy/pkg/cache"
"github.com/ftl/rigproxy/pkg/netio"
"github.com/ftl/rigproxy/pkg/protocol"
"github.com/ftl/rigproxy/pkg/proxy"
)
var (
destination = flag.StringP("destination", "d", "localhost:4534", "<host:port> of the destination rigctld server (default: localhost:4534)")
listen = flag.StringP("listen", "l", ":4532", "listening address of this proxy (default: :4532)")
lifetime = flag.DurationP("lifetime", "L", 200*time.Millisecond, "the lifetime of responses in the cache (default: 200ms)")
timeout = flag.DurationP("timeout", "t", 10*time.Second, "the timeout for network requests")
retry = flag.DurationP("retry", "r", 10*time.Second, "the retry interval")
trace = flag.BoolP("trace", "v", false, "trace the communication with the destination")
test = flag.BoolP("test", "T", false, "run test code")
)
func main() {
flag.Parse()
for {
if *test {
runTest()
return
}
loop()
<-time.After(*retry)
}
}
func loop() {
done := make(chan struct{})
defer func() {
select {
case <-done:
default:
close(done)
}
log.Println("loop done")
}()
out, err := net.Dial("tcp", *destination)
if err != nil {
log.Println(err)
return
}
defer out.Close()
log.Printf("connected to %s", *destination)
trx := protocol.NewTransceiver(netio.WithTimeout(out, *timeout))
trx.WhenDone(func() {
log.Println("transceiver stopped")
close(done)
})
cache := cache.NewWithLifetime(*lifetime)
l, err := net.Listen("tcp", *listen)
if err != nil {
log.Println(err)
return
}
go func() {
<-done
l.Close()
}()
for {
conn, err := l.Accept()
if err != nil {
log.Println(err)
return
}
go proxy.NewCached(conn, trx, cache, done, *trace)
}
}
func runTest() {
out, err := net.Dial("tcp", *destination)
if err != nil {
log.Println(err)
return
}
defer out.Close()
trx := protocol.NewTransceiver(out)
trx.WhenDone(func() {
log.Println("transceiver stopped")
})
for {
select {
case <-time.After(500 * time.Millisecond):
request := protocol.Request{Command: protocol.ShortCommand("f")}
startTime := time.Now()
response, err := trx.Send(context.Background(), request)
log.Printf("%v %v", response, time.Now().Sub(startTime))
if err != nil {
log.Print("polling frequency failed: ", err)
return
}
}
}
}