2020-01-22 13:02:06 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-09-17 23:39:15 +00:00
|
|
|
"crypto/tls"
|
2020-11-27 13:00:45 +00:00
|
|
|
"errors"
|
2020-01-22 13:02:06 +00:00
|
|
|
"fmt"
|
2020-11-27 13:00:45 +00:00
|
|
|
"io"
|
2021-09-17 23:39:15 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
2021-10-13 15:05:59 +00:00
|
|
|
"time"
|
2020-01-22 13:02:06 +00:00
|
|
|
|
2022-03-11 12:42:02 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2022-03-10 11:46:36 +00:00
|
|
|
"github.com/spf13/cobra"
|
2021-11-23 14:15:47 +00:00
|
|
|
"google.golang.org/grpc"
|
2022-07-15 13:48:09 +00:00
|
|
|
"google.golang.org/grpc/health/grpc_health_v1"
|
2022-03-10 11:46:36 +00:00
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
greflectsvc "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
|
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
"google.golang.org/protobuf/types/descriptorpb"
|
2020-11-08 18:28:33 +00:00
|
|
|
|
2023-07-07 23:33:10 +00:00
|
|
|
"go.linka.cloud/grpc-toolkit/client"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors/auth"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors/ban"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors/defaulter"
|
|
|
|
"go.linka.cloud/grpc-toolkit/interceptors/iface"
|
|
|
|
metrics2 "go.linka.cloud/grpc-toolkit/interceptors/metrics"
|
|
|
|
validation2 "go.linka.cloud/grpc-toolkit/interceptors/validation"
|
|
|
|
"go.linka.cloud/grpc-toolkit/logger"
|
|
|
|
"go.linka.cloud/grpc-toolkit/service"
|
2020-01-22 13:02:06 +00:00
|
|
|
)
|
|
|
|
|
2022-07-15 13:48:09 +00:00
|
|
|
var (
|
|
|
|
_ iface.UnaryInterceptor = (*GreeterHandler)(nil)
|
|
|
|
_ iface.StreamInterceptor = (*GreeterHandler)(nil)
|
|
|
|
)
|
|
|
|
|
2021-09-17 23:39:15 +00:00
|
|
|
type GreeterHandler struct {
|
2020-11-27 13:00:45 +00:00
|
|
|
UnimplementedGreeterServer
|
|
|
|
}
|
2020-01-22 13:02:06 +00:00
|
|
|
|
|
|
|
func hello(name string) string {
|
|
|
|
return fmt.Sprintf("Hello %s !", name)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *GreeterHandler) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
|
|
|
|
return &HelloReply{Message: hello(req.Name)}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *GreeterHandler) SayHelloStream(req *HelloStreamRequest, s Greeter_SayHelloStreamServer) error {
|
|
|
|
for i := int64(0); i < req.Count; i++ {
|
2020-11-27 13:00:45 +00:00
|
|
|
if err := s.Send(&HelloReply{Message: fmt.Sprintf("Hello %s (%d)!", req.Name, i+1)}); err != nil {
|
2020-01-22 13:02:06 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-09-17 23:39:15 +00:00
|
|
|
// time.Sleep(time.Second)
|
2020-01-22 13:02:06 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-07-15 13:48:09 +00:00
|
|
|
func (g *GreeterHandler) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
|
|
|
|
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
|
|
|
|
logger.C(ctx).Infof("called service interface unary interceptor")
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *GreeterHandler) StreamServerInterceptor() grpc.StreamServerInterceptor {
|
|
|
|
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
|
|
|
logger.C(ss.Context()).Infof("called service interface stream interceptor")
|
|
|
|
return handler(srv, ss)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-13 15:05:59 +00:00
|
|
|
func httpLogger(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
|
|
|
start := time.Now()
|
|
|
|
log := logger.From(request.Context()).WithFields(
|
|
|
|
"method", request.Method,
|
|
|
|
"host", request.Host,
|
|
|
|
"path", request.URL.Path,
|
|
|
|
"remoteAddress", request.RemoteAddr,
|
|
|
|
)
|
|
|
|
next.ServeHTTP(writer, request)
|
|
|
|
log.WithField("duration", time.Since(start)).Info()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-01-22 13:02:06 +00:00
|
|
|
func main() {
|
2022-03-10 11:46:36 +00:00
|
|
|
f, opts := service.NewFlagSet()
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "example",
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
run(opts)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
cmd.Flags().AddFlagSet(f)
|
|
|
|
cmd.Execute()
|
|
|
|
}
|
|
|
|
|
|
|
|
func run(opts ...service.Option) {
|
2020-11-08 18:28:33 +00:00
|
|
|
name := "greeter"
|
2021-11-22 13:04:47 +00:00
|
|
|
version := "v0.0.1"
|
2021-09-17 23:39:15 +00:00
|
|
|
secure := true
|
2020-11-08 18:28:33 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2022-03-10 11:46:36 +00:00
|
|
|
defer cancel()
|
2023-08-04 20:47:21 +00:00
|
|
|
log := logger.New().WithFields("service", name).WithReportCaller(true)
|
2022-03-10 11:46:36 +00:00
|
|
|
ctx = logger.Set(ctx, log)
|
2020-11-08 18:28:33 +00:00
|
|
|
done := make(chan struct{})
|
|
|
|
ready := make(chan struct{})
|
2020-01-22 20:20:18 +00:00
|
|
|
var svc service.Service
|
2020-01-22 13:02:06 +00:00
|
|
|
var err error
|
2022-11-06 21:51:03 +00:00
|
|
|
metrics := metrics2.DefaultInterceptors()
|
2021-11-21 13:58:49 +00:00
|
|
|
validation := validation2.NewInterceptors(true)
|
2021-11-21 15:13:43 +00:00
|
|
|
defaulter := defaulter.NewInterceptors()
|
2021-09-17 23:39:15 +00:00
|
|
|
address := "0.0.0.0:9991"
|
2022-03-10 11:46:36 +00:00
|
|
|
opts = append(opts, service.WithContext(ctx),
|
2020-11-08 18:28:33 +00:00
|
|
|
service.WithName(name),
|
2021-11-22 13:04:47 +00:00
|
|
|
service.WithVersion(version),
|
2021-09-17 23:39:15 +00:00
|
|
|
service.WithAddress(address),
|
2021-11-22 13:04:47 +00:00
|
|
|
// service.WithRegistry(mdns.NewRegistry()),
|
2020-08-07 08:59:27 +00:00
|
|
|
service.WithReflection(true),
|
2021-09-17 23:39:15 +00:00
|
|
|
service.WithSecure(secure),
|
2020-01-22 20:20:18 +00:00
|
|
|
service.WithAfterStart(func() error {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Info("Server listening on", svc.Options().Address())
|
2020-11-08 18:28:33 +00:00
|
|
|
close(ready)
|
2020-01-22 13:02:06 +00:00
|
|
|
return nil
|
|
|
|
}),
|
2020-01-22 20:20:18 +00:00
|
|
|
service.WithAfterStop(func() error {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Info("Stopping server")
|
2020-11-08 18:28:33 +00:00
|
|
|
close(done)
|
2020-01-22 13:02:06 +00:00
|
|
|
return nil
|
|
|
|
}),
|
2021-09-17 23:39:15 +00:00
|
|
|
service.WithGateway(RegisterGreeterHandler),
|
|
|
|
service.WithGatewayPrefix("/rest"),
|
|
|
|
service.WithGRPCWeb(true),
|
|
|
|
service.WithGRPCWebPrefix("/grpc"),
|
2021-10-13 15:05:59 +00:00
|
|
|
service.WithMiddlewares(httpLogger),
|
2022-06-24 09:47:09 +00:00
|
|
|
service.WithInterceptors(metrics),
|
2022-07-15 13:48:09 +00:00
|
|
|
service.WithServerInterceptors(
|
2022-12-07 13:09:36 +00:00
|
|
|
ban.NewInterceptors(ban.WithDefaultJailDuration(time.Second), ban.WithDefaultCallback(func(action ban.Action, actor string, rule *ban.Rule) error {
|
|
|
|
log.WithFields("action", action, "actor", actor, "rule", rule.Name).Info("ban callback")
|
|
|
|
return nil
|
|
|
|
})),
|
2022-07-15 13:48:09 +00:00
|
|
|
auth.NewServerInterceptors(auth.WithBasicValidators(func(ctx context.Context, user, password string) (context.Context, error) {
|
|
|
|
if !auth.Equals(user, "admin") || !auth.Equals(password, "admin") {
|
|
|
|
return ctx, fmt.Errorf("invalid user or password")
|
|
|
|
}
|
|
|
|
log.Infof("request authenticated")
|
|
|
|
return ctx, nil
|
|
|
|
})),
|
|
|
|
),
|
2022-06-24 09:47:09 +00:00
|
|
|
service.WithInterceptors(defaulter, validation),
|
2022-07-15 13:48:09 +00:00
|
|
|
// enable server interface interceptor
|
|
|
|
service.WithServerInterceptors(iface.New()),
|
2020-01-22 13:02:06 +00:00
|
|
|
)
|
2022-03-10 11:46:36 +00:00
|
|
|
svc, err = service.New(opts...)
|
2020-01-22 13:02:06 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-11-27 13:00:45 +00:00
|
|
|
RegisterGreeterServer(svc, &GreeterHandler{})
|
2022-11-06 21:51:03 +00:00
|
|
|
metrics.EnableHandlingTimeHistogram()
|
2022-05-26 10:14:54 +00:00
|
|
|
metrics.Register(svc)
|
2020-11-08 18:28:33 +00:00
|
|
|
go func() {
|
|
|
|
if err := svc.Start(); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}()
|
2022-03-11 12:42:02 +00:00
|
|
|
go func() {
|
|
|
|
http.Handle("/metrics", promhttp.Handler())
|
|
|
|
if err := http.ListenAndServe(":9992", nil); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}()
|
2020-11-08 18:28:33 +00:00
|
|
|
<-ready
|
2022-09-27 15:06:18 +00:00
|
|
|
copts := []client.Option{
|
2021-11-22 13:04:47 +00:00
|
|
|
// client.WithName(name),
|
|
|
|
// client.WithVersion(version),
|
|
|
|
client.WithAddress("localhost:9991"),
|
|
|
|
// client.WithRegistry(mdns.NewRegistry()),
|
2021-09-17 23:39:15 +00:00
|
|
|
client.WithSecure(secure),
|
2021-11-23 14:15:47 +00:00
|
|
|
client.WithUnaryInterceptors(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
|
|
|
logger.From(ctx).WithFields("party", "client", "method", method).Info(req)
|
|
|
|
return invoker(ctx, method, req, reply, cc, opts...)
|
|
|
|
}),
|
2022-09-27 15:06:18 +00:00
|
|
|
}
|
|
|
|
s, err := client.New(copts...)
|
2020-11-08 18:28:33 +00:00
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
2020-11-08 18:28:33 +00:00
|
|
|
}
|
2020-11-27 13:00:45 +00:00
|
|
|
g := NewGreeterClient(s)
|
2022-07-15 13:48:09 +00:00
|
|
|
h := grpc_health_v1.NewHealthClient(s)
|
2022-12-07 13:09:36 +00:00
|
|
|
for i := 0; i < 5; i++ {
|
2022-09-27 15:06:18 +00:00
|
|
|
_, err := h.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
} else {
|
|
|
|
log.Fatalf("expected error")
|
|
|
|
}
|
|
|
|
}
|
2022-12-07 13:09:36 +00:00
|
|
|
log.Infof("waiting for unban")
|
|
|
|
time.Sleep(time.Second)
|
2022-09-27 15:06:18 +00:00
|
|
|
s, err = client.New(append(copts, client.WithInterceptors(auth.NewBasicAuthClientIntereptors("admin", "admin")))...)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
g = NewGreeterClient(s)
|
|
|
|
h = grpc_health_v1.NewHealthClient(s)
|
|
|
|
hres, err := h.Check(ctx, &grpc_health_v1.HealthCheckRequest{Service: "helloworld.Greeter"})
|
2022-07-15 13:48:09 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
log.Infof("status: %v", hres.Status)
|
|
|
|
|
2022-03-10 11:46:36 +00:00
|
|
|
md := metadata.MD{}
|
|
|
|
res, err := g.SayHello(ctx, &HelloRequest{Name: "test"}, grpc.Header(&md))
|
2020-11-08 18:28:33 +00:00
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
2020-01-22 13:02:06 +00:00
|
|
|
}
|
2022-03-10 11:46:36 +00:00
|
|
|
logMetadata(ctx, md)
|
|
|
|
log.Infof("received message: %s", res.Message)
|
|
|
|
md = metadata.MD{}
|
|
|
|
res, err = g.SayHello(ctx, &HelloRequest{}, grpc.Header(&md))
|
2021-11-21 13:58:49 +00:00
|
|
|
if err == nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal("expected validation error")
|
2021-11-21 13:58:49 +00:00
|
|
|
}
|
2022-03-10 11:46:36 +00:00
|
|
|
logMetadata(ctx, md)
|
|
|
|
stream, err := g.SayHelloStream(ctx, &HelloStreamRequest{Name: "test"}, grpc.Header(&md))
|
2020-11-27 13:00:45 +00:00
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
if md, err := stream.Header(); err == nil {
|
|
|
|
logMetadata(ctx, md)
|
2020-11-27 13:00:45 +00:00
|
|
|
}
|
|
|
|
for {
|
|
|
|
m, err := stream.Recv()
|
|
|
|
if errors.Is(err, io.EOF) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
2020-11-27 13:00:45 +00:00
|
|
|
}
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Infof("received stream message: %s", m.Message)
|
2020-11-27 13:00:45 +00:00
|
|
|
}
|
2021-09-17 23:39:15 +00:00
|
|
|
scheme := "http://"
|
|
|
|
if secure {
|
|
|
|
scheme = "https://"
|
|
|
|
}
|
|
|
|
httpc := &http.Client{
|
|
|
|
Transport: &http.Transport{
|
|
|
|
TLSClientConfig: &tls.Config{
|
|
|
|
InsecureSkipVerify: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
req := `{"name":"test"}`
|
|
|
|
|
|
|
|
do := func(url, contentType string) {
|
2022-06-24 09:47:09 +00:00
|
|
|
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(req))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
req.Header.Set("content-type", contentType)
|
|
|
|
req.Header.Set("authorization", auth.BasicAuth("admin", "admin"))
|
|
|
|
resp, err := httpc.Do(req)
|
2021-09-17 23:39:15 +00:00
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
2021-09-17 23:39:15 +00:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2023-03-11 11:27:30 +00:00
|
|
|
b, err := io.ReadAll(resp.Body)
|
2021-09-17 23:39:15 +00:00
|
|
|
if err != nil {
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Fatal(err)
|
2021-09-17 23:39:15 +00:00
|
|
|
}
|
2022-03-10 11:46:36 +00:00
|
|
|
log.Info(string(b))
|
2021-09-17 23:39:15 +00:00
|
|
|
}
|
2021-10-13 15:05:59 +00:00
|
|
|
do(scheme+address+"/rest/api/v1/greeter/hello", "application/json")
|
2021-09-17 23:39:15 +00:00
|
|
|
do(scheme+address+"/grpc/helloworld.Greeter/SayHello", "application/grpc-web+json")
|
2022-03-10 11:46:36 +00:00
|
|
|
|
|
|
|
if err := readSvcs(ctx, s); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2020-11-08 18:28:33 +00:00
|
|
|
cancel()
|
|
|
|
<-done
|
2020-01-22 13:02:06 +00:00
|
|
|
}
|
2022-03-10 11:46:36 +00:00
|
|
|
|
|
|
|
func logMetadata(ctx context.Context, md metadata.MD) {
|
|
|
|
log := logger.From(ctx)
|
|
|
|
for k, v := range md {
|
|
|
|
log.Infof("%s: %v", k, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func readSvcs(ctx context.Context, c client.Client) (err error) {
|
|
|
|
log := logger.From(ctx)
|
|
|
|
rc := greflectsvc.NewServerReflectionClient(c)
|
|
|
|
rstream, err := rc.ServerReflectionInfo(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err2 := rstream.CloseSend(); err2 != nil && err == nil {
|
|
|
|
err = err2
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
if err = rstream.Send(&greflectsvc.ServerReflectionRequest{MessageRequest: &greflectsvc.ServerReflectionRequest_ListServices{}}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
var rres *greflectsvc.ServerReflectionResponse
|
|
|
|
rres, err = rstream.Recv()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
rlist, ok := rres.MessageResponse.(*greflectsvc.ServerReflectionResponse_ListServicesResponse)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unexpected reflection response type: %T", rres.MessageResponse)
|
|
|
|
}
|
|
|
|
for _, v := range rlist.ListServicesResponse.Service {
|
|
|
|
if v.Name == "grpc.reflection.v1alpha.ServerReflection" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
parts := strings.Split(v.Name, ".")
|
|
|
|
if len(parts) < 2 {
|
|
|
|
return fmt.Errorf("malformed service name: %s", v.Name)
|
|
|
|
}
|
|
|
|
pkg := strings.Join(parts[:len(parts)-1], ".")
|
|
|
|
svc := parts[len(parts)-1]
|
|
|
|
if err = rstream.Send(&greflectsvc.ServerReflectionRequest{MessageRequest: &greflectsvc.ServerReflectionRequest_FileContainingSymbol{
|
|
|
|
FileContainingSymbol: v.Name,
|
|
|
|
}}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
rres, err = rstream.Recv()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
rfile, ok := rres.MessageResponse.(*greflectsvc.ServerReflectionResponse_FileDescriptorResponse)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unexpected reflection response type: %T", rres.MessageResponse)
|
|
|
|
}
|
|
|
|
fdps := make(map[string]*descriptorpb.DescriptorProto)
|
|
|
|
var sdp *descriptorpb.ServiceDescriptorProto
|
|
|
|
for _, v := range rfile.FileDescriptorResponse.FileDescriptorProto {
|
|
|
|
fdp := &descriptorpb.FileDescriptorProto{}
|
|
|
|
if err = proto.Unmarshal(v, fdp); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for _, s := range fdp.GetService() {
|
|
|
|
if fdp.GetPackage() == pkg && s.GetName() == svc {
|
|
|
|
if sdp != nil {
|
|
|
|
log.Warnf("service already found: %s.%s", fdp.GetPackage(), s.GetName())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
sdp = s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, m := range fdp.GetMessageType() {
|
|
|
|
fdps[fdp.GetPackage()+"."+m.GetName()] = m
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if sdp == nil {
|
|
|
|
return fmt.Errorf("%s: service not found", v.Name)
|
|
|
|
}
|
|
|
|
for _, m := range sdp.GetMethod() {
|
|
|
|
log.Infof("%s: %s", v.Name, m.GetName())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|