forked from tokopedia/gripmock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gripmock.go
169 lines (148 loc) · 4.37 KB
/
gripmock.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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"github.com/tokopedia/gripmock/stub"
)
func main() {
outputPointer := flag.String("o", "", "directory to output server.go. Default is $GOPATH/src/grpc/")
grpcPort := flag.String("grpc-port", "4770", "Port of gRPC tcp server")
grpcBindAddr := flag.String("grpc-listen", "", "Adress the gRPC server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine")
adminport := flag.String("admin-port", "4771", "Port of stub admin server")
adminBindAddr := flag.String("admin-listen", "", "Adress the admin server will bind to. Default to localhost, set to 0.0.0.0 to use from another machine")
stubPath := flag.String("stub", "", "Path where the stub files are (Optional)")
imports := flag.String("imports", "/protobuf", "comma separated imports path. default path /protobuf is where gripmock Dockerfile install WKT protos")
// for backwards compatibility
if os.Args[1] == "gripmock" {
os.Args = append(os.Args[:1], os.Args[2:]...)
}
flag.Parse()
fmt.Println("Starting GripMock")
output := *outputPointer
if output == "" {
if os.Getenv("GOPATH") == "" {
log.Fatal("output is not provided and GOPATH is empty")
}
output = os.Getenv("GOPATH") + "/src/grpc"
}
// for safety
output += "/"
if _, err := os.Stat(output); os.IsNotExist(err) {
os.Mkdir(output, os.ModePerm)
}
// run admin stub server
stub.RunStubServer(stub.Options{
StubPath: *stubPath,
Port: *adminport,
BindAddr: *adminBindAddr,
})
// parse proto files
protoPaths := flag.Args()
if len(protoPaths) == 0 {
log.Fatal("Need atleast one proto file")
}
importDirs := strings.Split(*imports, ",")
// generate pb.go and grpc server based on proto
generateProtoc(protocParam{
protoPath: protoPaths,
adminPort: *adminport,
grpcAddress: *grpcBindAddr,
grpcPort: *grpcPort,
output: output,
imports: importDirs,
})
// build the server
buildServer(output, protoPaths)
// and run
run, runerr := runGrpcServer(output)
var term = make(chan os.Signal)
signal.Notify(term, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT)
select {
case err := <-runerr:
log.Fatal(err)
case <-term:
fmt.Println("Stopping gRPC Server")
run.Process.Kill()
}
}
func getProtoName(path string) string {
paths := strings.Split(path, "/")
filename := paths[len(paths)-1]
return strings.Split(filename, ".")[0]
}
type protocParam struct {
protoPath []string
adminPort string
grpcAddress string
grpcPort string
output string
imports []string
}
func generateProtoc(param protocParam) {
protodirs := strings.Split(param.protoPath[0], "/")
protodir := ""
if len(protodirs) > 0 {
protodir = strings.Join(protodirs[:len(protodirs)-1], "/") + "/"
}
args := []string{"-I", protodir}
// include well-known-types
for _, i := range param.imports {
args = append(args, "-I", i)
}
args = append(args, param.protoPath...)
args = append(args, "--go_out=plugins=grpc:"+param.output)
args = append(args, fmt.Sprintf("--gripmock_out=admin-port=%s,grpc-address=%s,grpc-port=%s:%s",
param.adminPort, param.grpcAddress, param.grpcPort, param.output))
protoc := exec.Command("protoc", args...)
protoc.Stdout = os.Stdout
protoc.Stderr = os.Stderr
err := protoc.Run()
if err != nil {
log.Fatal("Fail on protoc ", err)
}
// change package to "main" on generated code
for _, proto := range param.protoPath {
protoname := getProtoName(proto)
sed := exec.Command("sed", "-i", `s/^package \w*$/package main/`, param.output+protoname+".pb.go")
sed.Stderr = os.Stderr
sed.Stdout = os.Stdout
err = sed.Run()
if err != nil {
log.Fatal("Fail on sed")
}
}
}
func buildServer(output string, protoPaths []string) {
args := []string{"build", "-o", output + "grpcserver", output + "server.go"}
for _, path := range protoPaths {
args = append(args, output+getProtoName(path)+".pb.go")
}
build := exec.Command("go", args...)
build.Stdout = os.Stdout
build.Stderr = os.Stderr
err := build.Run()
if err != nil {
log.Fatal(err)
}
}
func runGrpcServer(output string) (*exec.Cmd, <-chan error) {
run := exec.Command(output + "grpcserver")
run.Stdout = os.Stdout
run.Stderr = os.Stderr
err := run.Start()
if err != nil {
log.Fatal(err)
}
fmt.Printf("grpc server pid: %d\n", run.Process.Pid)
runerr := make(chan error)
go func() {
runerr <- run.Wait()
}()
return run, runerr
}