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 all 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
8 changes: 4 additions & 4 deletions cloudevents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ client the developers need to provide
cluster URL and appending the controller name. Similarly, a RESTful service can select a unique name or generate a
unique ID in the associated database for its source identification.
- `CloudEventsOptions`, it provides cloudevents clients to send/receive cloudevents based on different event
protocol. We have supported the MQTT protocol (`mqtt.NewSourceOptions`), developers can use it directly.
protocol. We have supported [MQTT protocol (`mqtt.NewSourceOptions`)](./generic/options/mqtt) and [gRPC protocol (`grpc.NewSourceOptions`)](./generic/options/grpc) developers can use it directly.

2. A resource lister (`generic.Lister`), it is used to list the resource objects on the source when resyncing the
resources between sources and agents, for example, a hub controller can list the resources from the resource informers,
Expand All @@ -39,7 +39,7 @@ package.
5. Resource handler methods (`generic.ResourceHandler`), they are used to handle the resources status after the client
received the resources status from agents.

for example:
for example, build a generic client on the source using MQTT protocol with the following code:

```golang
// build a client for the source1
Expand Down Expand Up @@ -71,7 +71,7 @@ this client the developers need to provide
agent name.
- `clusterName`, it is the name of a managed cluster on which the agent runs.
- `CloudEventsOptions`, it provides cloudevents clients to send/receive cloudevents based on different event
protocol. We have supported the MQTT protocol (`mqtt.NewAgentOptions`), developers can use it directly.
protocol. We have supported [MQTT protocol (`mqtt.NewAgentOptions`)](./generic/options/mqtt) and [gRPC protocol (`grpc.NewAgentOptions`)](./generic/options/grpc) , developers can use it directly.

2. A resource lister (`generic.Lister`), it is used to list the resource objects on a managed cluster when resyncing the
resources between sources and agents, for example, a work agent can list its works from its work informers.
Expand All @@ -88,7 +88,7 @@ package.
5. Resource handler methods (`generic.ResourceHandler`), they are used to handle the resources after the client received
the resources from sources.

for example:
for example, build a generic client on the source using MQTT protocol with the following code:

```golang
// build a client for a work agent on the cluster1
Expand Down
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)
}
})
}
}
Loading
Loading