/
main.go
199 lines (177 loc) · 4.16 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
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
package main
import (
"encoding/json"
"fmt"
"git-webhook-proxy/client/config"
"git-webhook-proxy/protocol"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/urfave/cli"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"time"
)
var (
configPath string
systemConfig *config.SystemConfig
beforePull = "git reset --hard && git checkout "
subscribeMap = make(map[string]*config.SubscribeConfig, 0)
)
func main() {
{
app := cli.NewApp()
app.Name = "git proxy client"
app.Usage = "client for git-webhook-proxy"
app.Version = "0.1.0"
app.Authors = []cli.Author{
{
Name: "yufu",
Email: "mxy@yufu.fun",
},
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "config, c",
Usage: "config path",
Value: "client/config.yaml",
Destination: &configPath,
},
}
app.Action = run
log.Infof("[MAIN]Run start")
err := app.Run(os.Args)
if nil != err {
log.Errorf("[MAIN]Run error; " + err.Error())
}
}
}
func run(_ *cli.Context) {
var err error
systemConfig, err = config.LoadConfig(configPath)
if err != nil {
log.Fatalf("[MAIN]parse config error:%s", err.Error())
}
if systemConfig.Mode == "debug" {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
tcpAddr, err := net.ResolveTCPAddr("tcp4", systemConfig.Server)
if err != nil {
log.Fatalf("Fatal error: %s", err.Error())
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
log.Fatalf("Fatal error: %s", err.Error())
os.Exit(1)
}
log.Info("connect success")
subSocket(conn, systemConfig)
if systemConfig.HttpListen != "" {
go subHttp()
}
go heartbeat(conn)
readCon(conn)
}
func readCon(conn net.Conn) {
defer conn.Close()
tmpBuffer := make([]byte, 0)
buffer := make([]byte, 1024)
for {
n, err := conn.Read(buffer)
if err != nil {
log.Errorf("connection error: %s, %s", conn.RemoteAddr().String(), err.Error())
conn.Close()
return
}
protocolId, msg := protocol.DePack(append(tmpBuffer, buffer[:n]...))
if protocolId < 0 {
tmpBuffer = make([]byte, 0)
} else if protocolId == 0 {
tmpBuffer = append(tmpBuffer, buffer[:n]...)
} else {
log.Debugf("got message from server: %d,%s", protocolId, msg)
go deal(string(msg))
tmpBuffer = make([]byte, 0)
}
}
}
func subSocket(conn net.Conn, config *config.SystemConfig) {
urls := make([]string, 0)
for k, subscribe := range config.Subscribes {
subscribeMap[subscribe.Url] = &config.Subscribes[k]
urls = append(urls, subscribe.Url)
}
msg, _ := json.Marshal(urls)
conn.Write(protocol.EnPack(101, msg))
log.Infof("subscribes:%s", msg)
}
func subHttp() {
mux := http.NewServeMux()
mux.HandleFunc("/notify", NotifyHandler)
//api接口
httpServer := &http.Server{
Addr: systemConfig.HttpListen,
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
httpServer.ListenAndServe()
}
func NotifyHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
log.Debugf("notify :%s", body)
go deal(string(body))
w.Write([]byte("ok"))
}
func deal(body string) {
res := gjson.Parse(body)
url := res.Get("repository.ssh_url").String()
if url == "" {
url = res.Get("project.ssh_url").String()
}
if url == "" {
return
}
var subscribed *config.SubscribeConfig
var ok bool
if subscribed, ok = subscribeMap[url]; !ok {
log.Infof("un subscribed url:%s", url)
return
}
branch := res.Get("ref").String()
if branch != "refs/heads/" + subscribed.Branch {
log.Infof("branch not match:%s|%s|%s", url, branch, subscribed.Branch)
return
}
log.Infof("notify url:%s", url)
command := fmt.Sprintf("%s && git pull", beforePull)
log.Infof("cmd:%s", command)
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/C", command)
} else {
cmd = exec.Command("sh", "-c", command)
}
cmd.Dir = subscribed.Directory
out, err := cmd.Output()
if err != nil {
fmt.Println(err)
}
log.Infof("cmd output:%s", out)
}
func heartbeat(conn net.Conn) {
tick := time.NewTicker(time.Minute)
for {
select {
case <-tick.C:
conn.Write(protocol.EnPack(protocol.Heartbeat , []byte("ping")))
}
}
}