-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.go
106 lines (95 loc) · 2.08 KB
/
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
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
package main
import (
"bufio"
"go-deploy/config"
"go-deploy/ctrl"
"log"
"net"
"net/http"
"time"
)
func main() {
//start http server
log.Printf("Start http server listening %s", config.C.ListenHttp)
http.HandleFunc("/", ctrl.Index)
http.HandleFunc("/list", ctrl.List)
http.HandleFunc("/deply", ctrl.Deply)
http.HandleFunc("/rollback", ctrl.Rollback)
http.HandleFunc("/showlog", ctrl.ShowLog)
s := &http.Server{
Addr: config.C.ListenHttp,
Handler: http.DefaultServeMux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
if err := s.ListenAndServe(); err != nil {
log.Println(err)
}
}()
for addr := range config.C.UniqAddr {
go Ping(addr)
}
//block
ticker := time.Tick(time.Second * 10)
for {
select {
case <-ticker:
}
}
}
func Ping(addr string) {
for {
func() {
//connect to this socket
conn, err := net.Dial("tcp", addr)
if err != nil {
log.Println("Error connect to client:", err)
return
}
//connect success
setClientOnlineStatus(addr, true)
//remote client closed
defer func() {
setClientOnlineStatus(addr, false)
conn.Close()
}()
//read message from client
go func(conn net.Conn) {
defer conn.Close()
for {
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
log.Println("Client closed", err.Error())
return
}
log.Print(conn.RemoteAddr(), " -> Message Received from client:", message)
}
}(conn)
ticker := time.Tick(time.Second * 15)
for {
select {
case <-ticker:
conn.SetWriteDeadline(time.Now().Add(3 * time.Second))
_, err := conn.Write([]byte("PING\n"))
if err != nil {
log.Println("Error writing to stream:", err)
return
}
}
}
}()
time.Sleep(time.Second * 5)
}
}
//set client online or offline
func setClientOnlineStatus(addr string, online bool) {
for key, app := range config.C.Apps {
for k, node := range app.Node {
if node.Addr == addr {
config.C.Apps[key].Node[k].Online = online
}
}
}
}