forked from osheroff/onetimeserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
64 lines (56 loc) · 1015 Bytes
/
server.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
package onetimeserver
import (
"fmt"
"math/rand"
"net"
"os"
"os/signal"
"syscall"
"time"
)
type Server interface {
Boot([]string) (map[string]interface{}, error)
Pid() int
Port() int
Kill(bool)
String() string
}
func TryPort(tryPort int) int {
conn, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", tryPort))
if err == nil {
conn.Close()
return tryPort
}
return 0
}
func GetPort() int {
for true {
tryPort := TryPort(rand.Intn(55000) + 9000)
if tryPort > 0 {
return tryPort
}
}
return 0
}
func pidExists(pid int) bool {
proc, err := os.FindProcess(pid)
if err != nil {
return false
}
err = proc.Signal(syscall.Signal(0))
return err == nil
}
func WatchServer(ppid int, server Server, cleanup bool) {
channel := make(chan os.Signal, 1)
signal.Notify(channel, os.Interrupt, os.Kill)
go func() {
for true {
if !pidExists(ppid) || !pidExists(server.Pid()) {
channel <- os.Kill
}
time.Sleep(1 * time.Second)
}
}()
<-channel
server.Kill(cleanup)
}