-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceutil.go
206 lines (175 loc) · 6.01 KB
/
serviceutil.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
// Package serviceutil provides service helper functions
package serviceutil
import (
"context"
"database/sql"
"fmt"
"net"
"net/http"
"sync"
"github.com/apex/log"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
const metricsPublishPort string = "8080"
const restPublishPort string = "8081"
const grpcPublishPort string = "8090"
// ErrInvalidArgument indicates, that one or more provided arguments are invalid, e.g. required data is missing
var ErrInvalidArgument = errors.New("One ore more request arguments are invalid")
// Service defines values to start a GRPC (and a REST) service
type Service struct {
Name string
GrpcPublishPort string
GrpcOptions []grpc.ServerOption
RestPort string
MetricsPort string
WaitGroup sync.WaitGroup
Client interface{}
NewClientFunc func(*grpc.ClientConn) interface{}
RegisterServerFunc func(s *grpc.Server, srv interface{})
RegisterClientFunc func(ctx context.Context, mux *runtime.ServeMux, client interface{}) error
Service interface{}
ServeHTTP bool // enables REST endpoints
SwaggerJsonPath string
}
// Start runs service with GRPC and REST service endpoints.
// REST is served if Service.ServeHttp is true (currently fixed on port 8080)
func (service *Service) Start() {
if service.MetricsPort == "" {
service.MetricsPort = metricsPublishPort
}
if service.RestPort == "" {
service.RestPort = restPublishPort
}
if service.GrpcPublishPort == "" {
service.GrpcPublishPort = grpcPublishPort
}
//TODO check service config
// start http metrics server
go func() {
http.Handle("/metrics", promhttp.HandlerFor(
prometheus.DefaultGatherer,
promhttp.HandlerOpts{},
))
http.ListenAndServe(":"+service.MetricsPort, nil)
}()
// start grpc server
service.WaitGroup.Add(1)
go func() {
if err := service.startGRPC(); err != nil {
log.Fatal(err.Error())
}
service.WaitGroup.Done()
}()
// start http server with grpc <-> rest gateway
if service.ServeHTTP {
service.WaitGroup.Add(1)
go func() {
if err := service.startREST(); err != nil {
log.Fatal(err.Error())
}
service.WaitGroup.Done()
}()
}
log.Infof("Service [%v] started", service.Name)
}
func (service *Service) startREST() error {
// create top level context
ctx := context.Background()
// create context that's closed when cancel() ist called
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// connect to GRPC server
conn, err := grpc.Dial("localhost:"+service.GrpcPublishPort, grpc.WithInsecure())
if err != nil {
return fmt.Errorf("failed to dial GRPC service [%w]", err)
}
defer conn.Close()
// register grpc-gateway
rmux := runtime.NewServeMux()
client := service.NewClientFunc(conn)
err = service.RegisterClientFunc(ctx, rmux, client)
if err != nil {
return fmt.Errorf("failed to start HTTP service [%w]", err)
}
// serve swagger file
mux := http.NewServeMux()
mux.Handle("/", rmux)
if service.SwaggerJsonPath != "" {
log.Infof("Using %s as swagger.json", service.SwaggerJsonPath)
mux.HandleFunc("/swagger.json", func(writer http.ResponseWriter, request *http.Request) {
http.ServeFile(writer, request, service.SwaggerJsonPath)
})
} else {
log.Infof("No swagger.json specifed")
}
// serve swagger-ui
swaggerMux := http.NewServeMux()
swaggerMux.Handle("/", rmux)
fs := http.FileServer(http.Dir("web"))
mux.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui", fs))
log.Infof("HTTP server start listening on port %v", service.RestPort)
return http.ListenAndServe("0.0.0.0:"+service.RestPort, mux)
}
func (service *Service) startGRPC() error {
// start listening for grpc
listen, err := net.Listen("tcp", ":"+service.GrpcPublishPort)
if err != nil {
return fmt.Errorf("failed to create Listen for GRPC service [%w]", err)
}
// create new grpc server
server := grpc.NewServer(service.GrpcOptions...)
reflection.Register(server)
grpc.EnableTracing = true
// register service
service.RegisterServerFunc(server, service.Service)
log.Infof("GRPC server start listening on port %v", service.GrpcPublishPort)
return server.Serve(listen)
}
// GetServiceConnection establishes connection to GRPC service at given URL.
// We are not waiting, til the service is up (no grpc.WithBlock())
func GetServiceConnection(serviceAddress string) (service *grpc.ClientConn, err error) {
return GetServiceConnectionWithDialOptions(serviceAddress, grpc.WithInsecure())
}
// GetServiceConnectionWithDialOptions establishes connection to GRPC service at given URL with given dial options.
func GetServiceConnectionWithDialOptions(serviceAddress string, dialOptions ...grpc.DialOption) (service *grpc.ClientConn, err error) {
service, err = grpc.Dial(serviceAddress, dialOptions...)
if err != nil {
log.Errorf("Failed to connect to '%s'. %s", serviceAddress, err.Error())
return nil, err
}
log.Debugf("Connection established to service at '%s'", service.Target())
return service, nil
}
// AsGrpcError returns a GRPC error, mapping internal errors and returning
// codes.Internal as default error.
// The error is logged
// If the given err is nil AsGrpcError returns nil
func AsGrpcError(err error, message string, messageArgs ...interface{}) error {
if err == nil {
return nil
}
// format message
message = fmt.Sprintf(message, messageArgs)
// TODO add error mappings
var grpcErr error
switch {
case err == sql.ErrNoRows:
grpcErr = status.Errorf(codes.NotFound, "Instance not found")
case err == ErrInvalidArgument:
grpcErr = status.Errorf(codes.InvalidArgument, message)
default:
grpcErr = status.Errorf(codes.Internal, "An internal error occurred")
}
log.Errorf("MESSAGE: [%v] PUBLIC ERROR: [%v] INTERNAL ERROR: [%v]", message, grpcErr.Error(), err)
return grpcErr
}
// CloseContexts is deprecated
func CloseContexts() {
}