-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxyswap.go
445 lines (374 loc) · 9.07 KB
/
proxyswap.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"os/signal"
"sync"
"time"
)
const (
defaultRunningPath = "./running"
netType = "tcp"
targetPoll = time.Millisecond * 100
defaultSwapPath = "./swap"
defaultSwapPoll = 10
swapFileMode = 0666
)
//copies sourcePath to destPath (overwriting) with same permissions as source
func copyFile(sourcePath string, destPath string) (err error) {
sourceFile, err := os.Open(sourcePath)
if err != nil {
return
}
defer closeFmt(sourceFile, &err)
sourceInfo, err := sourceFile.Stat()
if err != nil {
return
}
destFile, err := os.Create(destPath)
if err != nil {
return
}
defer closeFmt(destFile, &err)
if err = os.Chmod(destPath, sourceInfo.Mode()); err != nil {
if rerr := removeIgnore(destPath); rerr != nil {
err = fmt.Errorf("%v\n%v", err, rerr)
}
return
}
if _, err = io.Copy(destFile, sourceFile); err != nil {
if rerr := removeIgnore(destPath); rerr != nil {
err = fmt.Errorf("%v\n%v", err, rerr)
}
}
return
}
//close and possibly combine the Close() error into err
func closeFmt(closer io.Closer, err *error) {
if cerr := closer.Close(); cerr != nil {
*err = fmt.Errorf("%v\n%v", *err, cerr)
}
}
//close and possibly print a line into the log package
func closeLog(closer io.Closer) {
if err := closer.Close(); err != nil {
log.Println(err)
}
}
//remove path, ignoring a doesnt exist error
func removeIgnore(path string) error {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
//copies src to dest, closes dest writes and then writes signal to done channel
func copyConn(src *net.TCPConn, dest *net.TCPConn, done *sync.WaitGroup) {
defer done.Done()
defer func() {
if err := dest.CloseWrite(); err != nil {
log.Println(err)
}
}()
//Closing read unneeded and sometimes causes errors
if _, err := io.Copy(dest, src); err != nil {
log.Println(err)
}
}
//copies connections bidirectionally (closing when finished), then calls Done() on wait group
func handle(conn *net.TCPConn, targetAddr *net.TCPAddr, done *sync.WaitGroup) {
defer done.Done()
defer closeLog(conn)
targetConn, err := net.DialTCP(netType, nil, targetAddr)
if err != nil {
log.Println(err)
return
}
defer closeLog(targetConn)
var copyDone sync.WaitGroup
copyDone.Add(2)
go copyConn(conn, targetConn, ©Done)
go copyConn(targetConn, conn, ©Done)
copyDone.Wait()
}
//signals an already started exec.Cmd with an interrupt and waits forever for its exit
func stopCmd(cmd *exec.Cmd) error {
if cmd == nil {
return nil
}
if err := cmd.Process.Signal(os.Interrupt); err != nil {
return err
}
_ = cmd.Wait()
return nil
}
type configuration struct {
targetPath string
targetArgs []string
targetAddr *net.TCPAddr
runningPath string
swapPath string
swapPoll time.Duration
}
func readConfig(configPath string) (configuration, error) {
//read config bytes
configBytes, err := ioutil.ReadFile(configPath)
if err != nil {
return configuration{}, err
}
//decode json
type jsonConfiguration struct {
ServerPath string
ServerArgs []string
ServerPort int
RunningPath string
SwapPath string
SwapPoll int
}
var jsonConfig jsonConfiguration
if err = json.Unmarshal(configBytes, &jsonConfig); err != nil {
return configuration{}, err
}
//set defaults
if jsonConfig.RunningPath == "" {
jsonConfig.RunningPath = defaultRunningPath
}
if jsonConfig.SwapPath == "" {
jsonConfig.SwapPath = defaultSwapPath
}
if jsonConfig.SwapPoll == 0 {
jsonConfig.SwapPoll = defaultSwapPoll
}
//check target path exists
if _, err := os.Stat(jsonConfig.ServerPath); err != nil {
return configuration{}, fmt.Errorf("Need a valid ServerPath")
}
if jsonConfig.ServerPort == 0 {
return configuration{}, fmt.Errorf("Need a valid ServerPort")
}
return configuration{
jsonConfig.ServerPath,
jsonConfig.ServerArgs,
&net.TCPAddr{nil, jsonConfig.ServerPort, ""},
jsonConfig.RunningPath,
jsonConfig.SwapPath,
time.Second * time.Duration(jsonConfig.SwapPoll),
}, nil
}
type swapper struct {
configPath string
config configuration
server *server
shutdown chan bool
done sync.WaitGroup
target *exec.Cmd
}
func startSwapper(configPath string, server *server) (*swapper, error) {
config, err := readConfig(configPath)
if err != nil {
return &swapper{}, err
}
s := swapper{configPath, config, server, make(chan bool), sync.WaitGroup{}, nil}
//swap first time
s.swap()
s.done.Add(1)
go s.run()
return &s, nil
}
func (s *swapper) stop() error {
close(s.shutdown)
s.done.Wait()
if err := removeIgnore(s.config.swapPath); err != nil {
return err
}
if err := removeIgnore(s.config.runningPath); err != nil {
return err
}
return nil
}
func (s *swapper) swap() error {
log.Println("Swapping")
s.server.pause()
if err := stopCmd(s.target); err != nil {
return err
}
//remove old swap and running
if err := removeIgnore(s.config.swapPath); err != nil {
return err
}
if err := removeIgnore(s.config.runningPath); err != nil {
return err
}
//re-read config from file
if config, err := readConfig(s.configPath); err != nil {
return err
} else {
s.config = config
}
//create swap
if err := removeIgnore(s.config.swapPath); err != nil {
return err
}
if err := ioutil.WriteFile(s.config.swapPath, []byte{}, swapFileMode); err != nil {
return err
}
//copy target to running
if err := copyFile(s.config.targetPath, s.config.runningPath); err != nil {
return err
}
//start other and redirect its output to ours
s.target = exec.Command(s.config.runningPath, s.config.targetArgs...)
targetOut, err := s.target.StdoutPipe()
if err != nil {
return err
}
targetErr, err := s.target.StderrPipe()
if err != nil {
return err
}
go io.Copy(os.Stdout, targetOut)
go io.Copy(os.Stderr, targetErr)
if err := s.target.Start(); err != nil {
return err
}
//wait until server responds
for {
if _, err := net.DialTCP(netType, nil, s.config.targetAddr); err == nil {
break
}
time.Sleep(targetPoll)
}
if err := s.server.unpause(); err != nil {
return err
}
log.Println("Swapped")
return nil
}
func (s *swapper) run() {
defer s.done.Done()
ticker := time.Tick(s.config.swapPoll)
last := time.Now()
for {
select {
case <-s.shutdown:
if err := stopCmd(s.target); err != nil {
log.Panicln(err)
}
return
case <-ticker:
//get swap modified
info, err := os.Stat(s.config.swapPath)
if err != nil {
log.Println(err)
continue
}
//compare modified to current time
current := info.ModTime()
if !current.After(last) {
continue
}
if err := s.swap(); err != nil {
log.Panicln(err)
}
ticker = time.Tick(s.config.swapPoll) //in case poll changed on config reload in swap()
last = time.Now() //swap file is rewritten in swap(), so mod time changes
}
}
}
type server struct {
configPath string
config configuration
listener *net.TCPListener
pauseLock sync.Mutex
handlersDone sync.WaitGroup
done sync.WaitGroup
}
func startServer(configPath string, listenPort int) (*server, error) {
config, err := readConfig(configPath)
if err != nil {
return &server{}, err
}
listener, err := net.ListenTCP(netType, &net.TCPAddr{nil, listenPort, ""})
if err != nil {
return &server{}, err
}
s := server{configPath, config, listener, sync.Mutex{}, sync.WaitGroup{}, sync.WaitGroup{}}
s.done.Add(1)
go s.run()
return &s, nil
}
func (s *server) stop() error {
if err := s.listener.SetDeadline(time.Now()); err != nil {
return err
}
s.handlersDone.Wait()
s.done.Wait()
if err := s.listener.Close(); err != nil {
return err
}
return nil
}
func (s *server) pause() {
s.pauseLock.Lock()
s.handlersDone.Wait()
}
func (s *server) unpause() error {
//re-read config
if config, err := readConfig(s.configPath); err != nil {
return err
} else {
s.config = config
}
s.pauseLock.Unlock()
return nil
}
func (s *server) run() {
defer s.done.Done()
for {
conn, err := s.listener.AcceptTCP()
if err == nil {
s.pauseLock.Lock()
s.handlersDone.Add(1)
go handle(conn, s.config.targetAddr, &s.handlersDone)
s.pauseLock.Unlock()
continue
}
if opErr, ok := err.(*net.OpError); !ok || !opErr.Timeout() {
log.Panicln(err)
}
return
}
}
func main() {
var configPath string
var listenPort int
flag.IntVar(&listenPort, "listenPort", 8880, "Listen port")
flag.StringVar(&configPath, "configPath", "", "Configuration file path")
flag.Parse()
server, err := startServer(configPath, listenPort)
if err != nil {
log.Panicln(err)
}
swapper, err := startSwapper(configPath, server)
if err != nil {
log.Panicln(err)
}
osSignal := make(chan os.Signal, 1) //must use buffer of 1 since we ask to notify before we start waiting
signal.Notify(osSignal, os.Interrupt, os.Kill)
<-osSignal
log.Println("Stopping")
if err := server.stop(); err != nil { //stop server first so we don't kill the target process while still serving
log.Panicln(err)
}
if err := swapper.stop(); err != nil {
log.Panicln(err)
}
log.Println("Stopped")
}