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

✨ add grpc option for cloudevents client. #302

Merged
Show file tree
Hide file tree
Changes from 5 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
76 changes: 76 additions & 0 deletions cloudevents/generic/options/grpc/agentoptions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package grpc

import (
"context"
"fmt"
"strings"

cloudevents "github.com/cloudevents/sdk-go/v2"
cecontext "github.com/cloudevents/sdk-go/v2/context"

"open-cluster-management.io/api/cloudevents/generic/options"
"open-cluster-management.io/api/cloudevents/generic/options/grpc/protocol"
"open-cluster-management.io/api/cloudevents/generic/types"
)

type grpcAgentOptions struct {
GRPCOptions
errorChan chan error // grpc client connection doesn't have error channel, it will handle reconnecting automatically
clusterName string
}

func NewAgentOptions(grpcOptions *GRPCOptions, clusterName, agentID string) *options.CloudEventsAgentOptions {
return &options.CloudEventsAgentOptions{
CloudEventsOptions: &grpcAgentOptions{
GRPCOptions: *grpcOptions,
errorChan: make(chan error),
clusterName: clusterName,
},
AgentID: agentID,
ClusterName: clusterName,
}
}

func (o *grpcAgentOptions) WithContext(ctx context.Context, evtCtx cloudevents.EventContext) (context.Context, error) {
eventType, err := types.ParseCloudEventsType(evtCtx.GetType())
Copy link
Member

Choose a reason for hiding this comment

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

do we need this for grpc?

Copy link
Member Author

Choose a reason for hiding this comment

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

We require this information to assign the topic for event publish, and the topic will be included in the gRPC publish request, see:

message PublishRequest {
// Required. The topic to which event should be published.
// Format is `myhome/groundfloor/livingroom/temperature`.
string topic = 1;
CloudEvent event = 2;
}

if err != nil {
return nil, fmt.Errorf("unsupported event type %s, %v", eventType, err)
}

if eventType.Action == types.ResyncRequestAction {
// agent publishes event to spec resync topic to request to get resources spec from all sources
topic := strings.Replace(SpecResyncTopic, "+", o.clusterName, -1)
return cecontext.WithTopic(ctx, topic), nil
}

// agent publishes event to status topic to send the resource status from a specified cluster
originalSource, err := evtCtx.GetExtension(types.ExtensionOriginalSource)
if err != nil {
return nil, err
}

statusTopic := strings.Replace(StatusTopic, "+", fmt.Sprintf("%s", originalSource), 1)
statusTopic = strings.Replace(statusTopic, "+", o.clusterName, -1)
return cecontext.WithTopic(ctx, statusTopic), nil
}

func (o *grpcAgentOptions) Client(ctx context.Context) (cloudevents.Client, error) {
receiver, err := o.GetCloudEventsClient(
ctx,
protocol.WithPublishOption(&protocol.PublishOption{}),
protocol.WithSubscribeOption(&protocol.SubscribeOption{
Topics: []string{
replaceNth(SpecTopic, "+", o.clusterName, 2), // receiving the resources spec from sources with spec topic
StatusResyncTopic, // receiving the resources status resync request from sources with status resync topic
},
}),
)
if err != nil {
return nil, err
}
return receiver, nil
}

func (o *grpcAgentOptions) ErrorChan() <-chan error {
return o.errorChan
}
123 changes: 123 additions & 0 deletions cloudevents/generic/options/grpc/agentoptions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package grpc

import (
"context"
"testing"

cloudevents "github.com/cloudevents/sdk-go/v2"
cloudeventscontext "github.com/cloudevents/sdk-go/v2/context"

"open-cluster-management.io/api/cloudevents/generic/types"
)

var mockEventDataType = types.CloudEventsDataType{
Group: "resources.test",
Version: "v1",
Resource: "mockresources",
}

func TestAgentContext(t *testing.T) {
cases := []struct {
name string
event cloudevents.Event
expectedTopic string
assertError func(error)
}{
{
name: "unsupported event",
event: func() cloudevents.Event {
evt := cloudevents.NewEvent()
evt.SetType("unsupported")
return evt
}(),
assertError: func(err error) {
if err == nil {
t.Errorf("expected error, but failed")
}
},
},
{
name: "resync specs",
event: func() cloudevents.Event {
eventType := types.CloudEventsType{
CloudEventsDataType: mockEventDataType,
SubResource: types.SubResourceSpec,
Action: types.ResyncRequestAction,
}

evt := cloudevents.NewEvent()
evt.SetType(eventType.String())
evt.SetExtension("clustername", "cluster1")
return evt
}(),
expectedTopic: "sources/clusters/cluster1/specresync",
assertError: func(err error) {
if err != nil {
t.Errorf("unexpected error %v", err)
}
},
},
{
name: "send status no original source",
event: func() cloudevents.Event {
eventType := types.CloudEventsType{
CloudEventsDataType: mockEventDataType,
SubResource: types.SubResourceStatus,
Action: "test",
}

evt := cloudevents.NewEvent()
evt.SetSource("hub1")
evt.SetType(eventType.String())
return evt
}(),
assertError: func(err error) {
if err == nil {
t.Errorf("expected error, but failed")
}
},
},
{
name: "send status",
event: func() cloudevents.Event {
eventType := types.CloudEventsType{
CloudEventsDataType: mockEventDataType,
SubResource: types.SubResourceStatus,
Action: "test",
}

evt := cloudevents.NewEvent()
evt.SetSource("agent")
evt.SetType(eventType.String())
evt.SetExtension("originalsource", "hub1")
return evt
}(),
expectedTopic: "sources/hub1/clusters/cluster1/status",
assertError: func(err error) {
if err != nil {
t.Errorf("unexpected error %v", err)
}
},
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
agentOptions := &grpcAgentOptions{clusterName: "cluster1"}
ctx, err := agentOptions.WithContext(context.TODO(), c.event.Context)
c.assertError(err)

topic := func(ctx context.Context) string {
if ctx == nil {
return ""
}

return cloudeventscontext.TopicFrom(ctx)
}(ctx)

if topic != c.expectedTopic {
t.Errorf("expected %s, but got %s", c.expectedTopic, topic)
}
})
}
}
166 changes: 166 additions & 0 deletions cloudevents/generic/options/grpc/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package grpc

import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"strings"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/yaml.v2"

cloudevents "github.com/cloudevents/sdk-go/v2"

"open-cluster-management.io/api/cloudevents/generic/options/grpc/protocol"
)

const (
Copy link
Member

Choose a reason for hiding this comment

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

move these topics to a common file?

Copy link
Member Author

Choose a reason for hiding this comment

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

Currently, the topic structure for gRPC aligns with MQTT, but when we have a third option like Kafka, that would need a distinct pattern for topics. In that case, a common file for topics becomes unfeasible, make sense?

Copy link
Member

Choose a reason for hiding this comment

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

yeah, but I think the ideal situation is to have unified topics :), we can keep the topics in each option firstly

Copy link
Member Author

Choose a reason for hiding this comment

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

OK, let's organize topics within each option for now and and see if we can have a unified topics in the future.

// SpecTopic is a pubsub topic for resource spec.
SpecTopic = "sources/+/clusters/+/spec"

// StatusTopic is a pubsub topic for resource status.
StatusTopic = "sources/+/clusters/+/status"

// SpecResyncTopic is a pubsub topic for resource spec resync.
SpecResyncTopic = "sources/clusters/+/specresync"

// StatusResyncTopic is a pubsub topic for resource status resync.
StatusResyncTopic = "sources/+/clusters/statusresync"
)

// GRPCOptions holds the options that are used to build gRPC client.
type GRPCOptions struct {
URL string
CAFile string
ClientCertFile string
ClientKeyFile string
}

// GRPCConfig holds the information needed to build connect to gRPC server as a given user.
type GRPCConfig struct {
// URL is the address of the gRPC server (host:port).
URL string `json:"url" yaml:"url"`
// CAFile is the file path to a cert file for the gRPC server certificate authority.
CAFile string `json:"caFile,omitempty" yaml:"caFile,omitempty"`
// ClientCertFile is the file path to a client cert file for TLS.
ClientCertFile string `json:"clientCertFile,omitempty" yaml:"clientCertFile,omitempty"`
// ClientKeyFile is the file path to a client key file for TLS.
ClientKeyFile string `json:"clientKeyFile,omitempty" yaml:"clientKeyFile,omitempty"`
}

// BuildGRPCOptionsFromFlags builds configs from a config filepath.
func BuildGRPCOptionsFromFlags(configPath string) (*GRPCOptions, error) {
configData, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}

config := &GRPCConfig{}
if err := yaml.Unmarshal(configData, config); err != nil {
return nil, err
}

if config.URL == "" {
return nil, fmt.Errorf("url is required")
}

if (config.ClientCertFile == "" && config.ClientKeyFile != "") ||
(config.ClientCertFile != "" && config.ClientKeyFile == "") {
return nil, fmt.Errorf("either both or none of clientCertFile and clientKeyFile must be set")
}
if config.ClientCertFile != "" && config.ClientKeyFile != "" && config.CAFile == "" {
return nil, fmt.Errorf("setting clientCertFile and clientKeyFile requires caFile")
}

return &GRPCOptions{
URL: config.URL,
CAFile: config.CAFile,
ClientCertFile: config.ClientCertFile,
ClientKeyFile: config.ClientKeyFile,
}, nil
}

func NewGRPCOptions() *GRPCOptions {
return &GRPCOptions{}
}

func (o *GRPCOptions) GetGRPCClientConn() (*grpc.ClientConn, error) {
if len(o.CAFile) != 0 {
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}

caPEM, err := os.ReadFile(o.CAFile)
if err != nil {
return nil, err
}

if ok := certPool.AppendCertsFromPEM(caPEM); !ok {
return nil, fmt.Errorf("invalid CA %s", o.CAFile)
}

clientCerts, err := tls.LoadX509KeyPair(o.ClientCertFile, o.ClientKeyFile)
if err != nil {
return nil, err
}

tlsConfig := &tls.Config{
Certificates: []tls.Certificate{clientCerts},
RootCAs: certPool,
MinVersion: tls.VersionTLS13,
MaxVersion: tls.VersionTLS13,
}

conn, err := grpc.Dial(o.URL, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
if err != nil {
return nil, fmt.Errorf("failed to connect to grpc server %s, %v", o.URL, err)
}

return conn, nil
}

conn, err := grpc.Dial(o.URL, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("failed to connect to grpc server %s, %v", o.URL, err)
}

return conn, nil
}

func (o *GRPCOptions) GetCloudEventsClient(ctx context.Context, clientOpts ...protocol.Option) (cloudevents.Client, error) {
conn, err := o.GetGRPCClientConn()
if err != nil {
return nil, err
}

opts := []protocol.Option{}
opts = append(opts, clientOpts...)
p, err := protocol.NewProtocol(conn, opts...)
if err != nil {
return nil, err
}

return cloudevents.NewClient(p)
}

// Replace the nth occurrence of old in str by new.
func replaceNth(str, old, new string, n int) string {
i := 0
for m := 1; m <= n; m++ {
x := strings.Index(str[i:], old)
if x < 0 {
break
}
i += x
if m == n {
return str[:i] + new + str[i+len(old):]
}
i += len(old)
}
return str
}
Loading
Loading