Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support grpc json protocol #582

Merged
merged 6 commits into from
Jun 14, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions protocol/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,58 @@ import (
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/opentracing/opentracing-go"
"google.golang.org/grpc"
"gopkg.in/yaml.v2"
)

import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/common/logger"
"github.com/apache/dubbo-go/config"
)

var (
clientConf *ClientConfig
)

func init() {
// load clientconfig from consumer_config
// default use grpc
defaultClientConfig := GetDefaultClientConfig()
clientConf = &defaultClientConfig
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the above two line codes is very strange. why now define a NewDefaultClientConfig() *ClientConfig?

Copy link
Contributor Author

@relaxedCat relaxedCat Jun 14, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok,use defer delay check instead

consumerConfig := config.GetConsumerConfig()

if consumerConfig.ApplicationConfig == nil {
return
}
protocolConf := config.GetConsumerConfig().ProtocolConf

if protocolConf == nil {
logger.Info("protocol_conf default use dubbo config")
} else {
grpcConf := protocolConf.(map[interface{}]interface{})[GRPC]
if grpcConf == nil {
logger.Warnf("grpcConf is nil")
return
}
grpcConfByte, err := yaml.Marshal(grpcConf)
if err != nil {
panic(err)
}
err = yaml.Unmarshal(grpcConfByte, clientConf)
if err != nil {
panic(err)
}
}

if clientConf == nil || len(clientConf.ContentSubType) == 0 {
clientConf = &defaultClientConfig
}
if err := clientConf.Validate(); err != nil {
panic(err)
}
}

// Client ...
type Client struct {
*grpc.ClientConn
Expand All @@ -43,9 +87,11 @@ type Client struct {
func NewClient(url common.URL) *Client {
// if global trace instance was set , it means trace function enabled. If not , will return Nooptracer
tracer := opentracing.GlobalTracer()
conn, err := grpc.Dial(url.Location, grpc.WithInsecure(), grpc.WithBlock(),
grpc.WithUnaryInterceptor(
otgrpc.OpenTracingClientInterceptor(tracer, otgrpc.LogPayloads())))
dailOpts := make([]grpc.DialOption, 0, 4)
dailOpts = append(dailOpts, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithUnaryInterceptor(
otgrpc.OpenTracingClientInterceptor(tracer, otgrpc.LogPayloads())),
grpc.WithDefaultCallOptions(grpc.CallContentSubtype(clientConf.ContentSubType)))
conn, err := grpc.Dial(url.Location, dailOpts...)
if err != nil {
panic(err)
}
Expand Down
78 changes: 78 additions & 0 deletions protocol/grpc/codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package grpc
relaxedCat marked this conversation as resolved.
Show resolved Hide resolved

import (
"bytes"
"encoding/json"
)

import (
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"google.golang.org/grpc/encoding"
)

const (
// json
CODEC_JSON = "json"
// proto
CODEC_PROTO = "proto"
)

func init() {
encoding.RegisterCodec(grpcJson{
Marshaler: jsonpb.Marshaler{
EmitDefaults: true,
OrigName: true,
},
})
}

// grpcJson ...
type grpcJson struct {
jsonpb.Marshaler
jsonpb.Unmarshaler
}

// implements grpc encoding package Codec interface method
func (_ grpcJson) Name() string {
return CODEC_JSON
}

// implements grpc encoding package Codec interface method
func (j grpcJson) Marshal(v interface{}) (out []byte, err error) {
if pm, ok := v.(proto.Message); ok {
b := new(bytes.Buffer)
err := j.Marshaler.Marshal(b, pm)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
return json.Marshal(v)
}

// implements grpc encoding package Codec interface method
func (j grpcJson) Unmarshal(data []byte, v interface{}) (err error) {
if pm, ok := v.(proto.Message); ok {
b := bytes.NewBuffer(data)
return j.Unmarshaler.Unmarshal(b, pm)
}
return json.Unmarshal(data, v)
}
65 changes: 65 additions & 0 deletions protocol/grpc/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package grpc

import (
perrors "github.com/pkg/errors"
)

type (
// ServerConfig
ServerConfig struct {
}

// ClientConfig
ClientConfig struct {
// content type, more information refer by https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
ContentSubType string `default:"proto" yaml:"content_sub_type" json:"content_sub_type,omitempty"`
}
)

// GetDefaultClientConfig ...
func GetDefaultClientConfig() ClientConfig {
fangyincheng marked this conversation as resolved.
Show resolved Hide resolved
return ClientConfig{
ContentSubType: CODEC_PROTO,
}
}

// GetDefaultServerConfig ...
func GetDefaultServerConfig() ServerConfig {
return ServerConfig{}
}

// GetClientConfig ...
func GetClientConfig() ClientConfig {
return ClientConfig{}
}

// clientConfig Validate ...
func (c *ClientConfig) Validate() error {
if c.ContentSubType != CODEC_JSON && c.ContentSubType != CODEC_PROTO {
return perrors.Errorf(" dubbo-go grpc codec currently only support proto、json, %s isn't supported,"+
" please check protocol content_sub_type config", c.ContentSubType)
}
return nil
}

// severConfig Validate ...
func (c *ServerConfig) Validate() error {
return nil
}
5 changes: 2 additions & 3 deletions protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ func (g *dubboGrpc) GenerateImports(file *generator.FileDescriptor) {
g.P(`dgrpc "github.com/apache/dubbo-go/protocol/grpc"`)
g.P(`"github.com/apache/dubbo-go/protocol/invocation"`)
g.P(`"github.com/apache/dubbo-go/protocol"`)
g.P(`"github.com/apache/dubbo-go/config"`)
g.P(` ) `)
}

Expand Down Expand Up @@ -266,7 +265,7 @@ func (g *dubboGrpc) generateServerMethod(servName, fullServName string, method *
g.P(`invo := invocation.NewRPCInvocation("`, methName, `", args, nil)`)

g.P("if interceptor == nil {")
g.P("result := base.GetProxyImpl().Invoke(invo)")
g.P("result := base.GetProxyImpl().Invoke(context.Background(), invo)")
g.P("return result.Result(), result.Error()")
g.P("}")

Expand All @@ -276,7 +275,7 @@ func (g *dubboGrpc) generateServerMethod(servName, fullServName string, method *
g.P("}")

g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
g.P("result := base.GetProxyImpl().Invoke(invo)")
g.P("result := base.GetProxyImpl().Invoke(context.Background(), invo)")
g.P("return result.Result(), result.Error()")
g.P("}")

Expand Down