Skip to content

Commit

Permalink
feat:add tls config & healthProbe
Browse files Browse the repository at this point in the history
  • Loading branch information
sjy-dv committed Jan 12, 2024
1 parent d7d6618 commit be4ab80
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 4 deletions.
16 changes: 13 additions & 3 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,19 @@ func RegisterBridgerClient(opt *options.Options) *BridgerAgent {
grpc.MaxCallSendMsgSize(maxSendMsgSize),
),
}
if opt.Credentials {
clientOpts = append(clientOpts, grpc.WithTransportCredentials(
credentials.NewTLS(&tls.Config{})))
if opt.Credentials.Enable {
if opt.Credentials.TLS != nil {
clientOpts = append(clientOpts, grpc.WithTransportCredentials(
credentials.NewTLS(opt.Credentials.TLS.Clone()),
))
} else if opt.Credentials.Cred != nil {
clientOpts = append(clientOpts, grpc.WithTransportCredentials(opt.Credentials.Cred))
} else {
clientOpts = append(clientOpts, grpc.WithTransportCredentials(
credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true,
})))
}
} else {
clientOpts = append(clientOpts, grpc.WithTransportCredentials(
insecure.NewCredentials()))
Expand Down
10 changes: 9 additions & 1 deletion client/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package options

import (
"context"
"crypto/tls"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)

type Options struct {
Expand All @@ -21,7 +23,13 @@ type Options struct {
KeepAliveTimeout time.Duration
KeepAliveTime time.Duration
MaxSession int32
Credentials bool
Credentials Credentials
}

type Credentials struct {
Enable bool
TLS *tls.Config
Cred credentials.TransportCredentials
}

const DefaultMsgSize = 104858000 // 10mb
Expand Down
68 changes: 68 additions & 0 deletions examples/tls/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"log"
"time"

"github.com/sjy-dv/bridger/client"
"github.com/sjy-dv/bridger/client/options"
"google.golang.org/grpc/credentials"
)

/*
If you are connecting to a pure gRPC server using SSL in Ingress,
simply set Enable to true without any additional configuration.
*/
func main() {
/*
not tls
*/
// bridgerClient := client.RegisterBridgerClient(&options.Options{
// Addr: "127.0.0.1:50051",
// MinChannelSize: 1,
// MaxChannelSize: 4,
// Timeout: time.Duration(time.Second * 5),
// })
// defer bridgerClient.Close()
/*
using ca.cert
*/
// b, _ := os.ReadFile("ca.cert")
// cp := x509.NewCertPool()
// if !cp.AppendCertsFromPEM(b) {
// panic("credentials: failed to append certificates")
// }
// bridgerClient := client.RegisterBridgerClient(&options.Options{
// Addr: "127.0.0.1:50051",
// MinChannelSize: 1,
// MaxChannelSize: 4,
// Timeout: time.Duration(time.Second * 5),
// Credentials: options.Credentials{
// Enable: true,
// TLS: &tls.Config{
// InsecureSkipVerify: false,
// RootCAs: cp,
// },
// },
// })
// defer bridgerClient.Close()
/*
using pem
*/
creds, err := credentials.NewClientTLSFromFile("service.pem", "")
if err != nil {
log.Fatalf("could not process the credentials: %v", err)
}
bridgerClient := client.RegisterBridgerClient(&options.Options{
Addr: "127.0.0.1:50051",
MinChannelSize: 1,
MaxChannelSize: 4,
Timeout: time.Duration(time.Second * 5),
Credentials: options.Credentials{
Enable: true,
Cred: creds,
},
})
defer bridgerClient.Close()
}
62 changes: 62 additions & 0 deletions examples/tls/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main

import (
"log"

"github.com/sjy-dv/bridger/server"
"github.com/sjy-dv/bridger/server/dispatcher"
"github.com/sjy-dv/bridger/server/options"
"google.golang.org/grpc/credentials"
)

func main() {
bridger := server.New()
creds, err := credentials.NewServerTLSFromFile("service.pem", "service.key")
if err != nil {
log.Fatalf("Failed to setup TLS: %v", err)
}
bridger.Register("/greetings", greetings)
bridger.Register("/greetings/withname",
greetingsWithHeaderName,
"is using metadata api")
bridger.RegisterBridgerServer(&options.Options{
Port: 50051,
ChainUnaryInterceptorLogger: true,
ChainStreamInterceptorLogger: true,
Credentials: options.Credentials{
Enable: true,
Cred: creds,
},
})
}

func greetings(dtx dispatcher.DispatchContext) *dispatcher.ResponseWriter {
var (
req = struct {
Msg string
}{}
err error
)
err = dtx.Bind(&req)
if err != nil {
return dtx.Error(err)
}
req.Msg = req.Msg + "\n" + "Me too.."
return dtx.Reply(&req)
}

func greetingsWithHeaderName(dtx dispatcher.DispatchContext) *dispatcher.ResponseWriter {
var (
req = struct {
Msg string
}{}
err error
)
err = dtx.Bind(&req)
if err != nil {
return dtx.Error(err)
}
name := dtx.GetMetadata("name")
req.Msg = "Hello " + name
return dtx.Reply(&req)
}
7 changes: 7 additions & 0 deletions server/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

_ "google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/keepalive"

grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
Expand Down Expand Up @@ -108,10 +109,16 @@ func (b *Bridger) RegisterBridgerServer(opt *options.Options) error {
Timeout: options.DefaultKeepAliveTimeout,
}))
}
if opt.Credentials.Enable && opt.Credentials.Cred != nil {
serverOptions = append(serverOptions, grpc.Creds(opt.Credentials.Cred.Clone()))
}
dispatch := rpcDispatcher{}
dispatch.DispatchService = &dispatchService{dispatch}
grpcServer := grpc.NewServer(serverOptions...)
pb.RegisterBridgerServer(grpcServer, dispatch.DispatchService)
if opt.HealthProbe {
grpc_health_v1.RegisterHealthServer(grpcServer, dispatch.healthCheck)
}
b.Logger.WithField("action", "grpc_startup").Infof("grpc server listening at %v", lis.Addr())
if err := grpcServer.Serve(lis); err != nil {
b.Logger.WithError(err)
Expand Down
8 changes: 8 additions & 0 deletions server/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)

type Options struct {
Expand All @@ -20,6 +21,13 @@ type Options struct {
KeepAliveTimeout time.Duration
KeepAliveTime time.Duration
EnforcementPolicyMinTime time.Duration
Credentials Credentials
HealthProbe bool // you must include health_probe binary
}

type Credentials struct {
Enable bool
Cred credentials.TransportCredentials
}

const (
Expand Down
16 changes: 16 additions & 0 deletions server/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,24 @@ import (
pb "github.com/sjy-dv/bridger/grpc/protocol/v0"

"github.com/sjy-dv/bridger/server/dispatcher"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/protobuf/types/known/emptypb"
)

type rpcDispatcher struct {
pb.UnimplementedBridgerServer
DispatchService *dispatchService
healthCheck *healthRpcService
}

type dispatchService struct {
rpcDispatcher
}

type healthRpcService struct {
rpcDispatcher
}

func (dispatch *rpcDispatcher) Ping(ctx context.Context, req *emptypb.Empty) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}
Expand Down Expand Up @@ -50,3 +56,13 @@ func (dispatch *rpcDispatcher) Dispatch(ctx context.Context, req *pb.PayloadEmit
res := <-c
return res.Result, res.Error
}

func (r healthRpcService) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
retval := &grpc_health_v1.HealthCheckResponse{}
retval.Status = grpc_health_v1.HealthCheckResponse_SERVING
return retval, nil
}

func (r healthRpcService) Watch(*grpc_health_v1.HealthCheckRequest, grpc_health_v1.Health_WatchServer) error {
return nil
}

0 comments on commit be4ab80

Please sign in to comment.