-
Notifications
You must be signed in to change notification settings - Fork 118
Add skeleton for gRPC Commander Service #408
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
Merged
kate-osborn
merged 2 commits into
feature/cp-dp-separation
from
feature/grpc-commander-skeleton
Feb 6, 2023
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package grpc | ||
|
||
import ( | ||
"context" | ||
"net" | ||
|
||
"github.com/go-logr/logr" | ||
sdkGrpc "github.com/nginx/agent/sdk/v2/grpc" | ||
"github.com/nginx/agent/sdk/v2/proto" | ||
"google.golang.org/grpc" | ||
) | ||
|
||
const protocol = "tcp" | ||
|
||
// Server is the gRPC server that handles requests from nginx agents. | ||
type Server struct { | ||
listener net.Listener | ||
server *grpc.Server | ||
logger logr.Logger | ||
} | ||
|
||
// NewServer accepts a logger, address, and CommandServer implementation. It creates a gRPC server listening on the | ||
// given address and registers the CommandServer implementation with the gRPC server. | ||
func NewServer(logger logr.Logger, address string, commander proto.CommanderServer) (*Server, error) { | ||
listener, err := net.Listen(protocol, address) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
grpcServer := grpc.NewServer(sdkGrpc.DefaultServerDialOptions...) | ||
|
||
proto.RegisterCommanderServer(grpcServer, commander) | ||
|
||
s := &Server{ | ||
logger: logger, | ||
listener: listener, | ||
server: grpcServer, | ||
} | ||
|
||
return s, nil | ||
} | ||
|
||
// Addr returns the address that the server is listening on. | ||
func (s *Server) Addr() string { | ||
return s.listener.Addr().String() | ||
} | ||
|
||
// Start starts the gRPC server. If the context is canceled, the server is stopped. | ||
func (s *Server) Start(ctx context.Context) error { | ||
go func() { | ||
<-ctx.Done() | ||
|
||
s.server.GracefulStop() | ||
s.logger.Info("gRPC server stopped") | ||
}() | ||
|
||
s.logger.Info("Starting gRPC Server", "addr", s.listener.Addr().String()) | ||
return s.server.Serve(s.listener) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package grpc_test | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/nginx/agent/sdk/v2/client" | ||
. "github.com/onsi/gomega" | ||
"github.com/onsi/gomega/gbytes" | ||
goGrpc "google.golang.org/grpc" | ||
"google.golang.org/grpc/credentials/insecure" | ||
"sigs.k8s.io/controller-runtime/pkg/log/zap" | ||
|
||
"github.com/nginxinc/nginx-kubernetes-gateway/internal/grpc" | ||
"github.com/nginxinc/nginx-kubernetes-gateway/internal/grpc/service" | ||
) | ||
|
||
// This test is pretty simple at the moment. We are only verifying that the server can be started, stopped, | ||
// and that the Commander implementation is registered with the server. | ||
// Once we add more functionality this test may become more meaningful. | ||
func TestServer(t *testing.T) { | ||
g := NewGomegaWithT(t) | ||
|
||
buf := gbytes.NewBuffer() | ||
logger := zap.New(zap.WriteTo(buf)) | ||
|
||
server, err := grpc.NewServer(logger, "localhost:0", service.NewCommander(logger)) | ||
g.Expect(err).To(BeNil()) | ||
g.Expect(server).ToNot(BeNil()) | ||
|
||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
go func() { | ||
g.Expect(server.Start(ctx)).To(Succeed()) | ||
}() | ||
|
||
commanderClient := client.NewCommanderClient() | ||
commanderClient.WithServer(server.Addr()) | ||
commanderClient.WithDialOptions(goGrpc.WithTransportCredentials(insecure.NewCredentials())) | ||
|
||
err = commanderClient.Connect(ctx) | ||
g.Expect(err).To(BeNil()) | ||
|
||
g.Eventually(buf).Should(gbytes.Say("Commander CommandChannel")) | ||
|
||
cancel() | ||
g.Eventually(buf).Should(gbytes.Say("gRPC server stopped")) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
package service | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"io" | ||
|
||
"github.com/go-logr/logr" | ||
"github.com/nginx/agent/sdk/v2/grpc" | ||
"github.com/nginx/agent/sdk/v2/proto" | ||
) | ||
|
||
// Commander implements the proto.CommanderServer interface. | ||
// This code is for demo purposes only. It's the least amount of code I could write to demonstrate that the agent and | ||
// control plane can communicate with each other. It is not the final version, so it isn't tested or commented. | ||
// Code is a version of https://github.com/nginx/agent/blob/main/sdk/examples/services/command_service.go | ||
type Commander struct { | ||
toClient chan *proto.Command | ||
logger logr.Logger | ||
} | ||
|
||
func NewCommander(logger logr.Logger) *Commander { | ||
return &Commander{ | ||
toClient: make(chan *proto.Command), | ||
logger: logger, | ||
} | ||
} | ||
|
||
func (c *Commander) CommandChannel(stream proto.Commander_CommandChannelServer) error { | ||
c.logger.Info("Commander CommandChannel") | ||
|
||
go c.handleReceive(stream) | ||
|
||
for { | ||
select { | ||
case out := <-c.toClient: | ||
err := stream.Send(out) | ||
if errors.Is(err, io.EOF) { | ||
c.logger.Info("CommandChannel EOF") | ||
return nil | ||
} | ||
if err != nil { | ||
c.logger.Error(err, "failed to send outgoing command") | ||
continue | ||
} | ||
case <-stream.Context().Done(): | ||
c.logger.Info("CommandChannel complete") | ||
return nil | ||
} | ||
} | ||
} | ||
|
||
func (c *Commander) Download(request *proto.DownloadRequest, _ proto.Commander_DownloadServer) error { | ||
c.logger.Info("Commander Download requested", "request", request.GetMeta()) | ||
|
||
return nil | ||
} | ||
|
||
func (c *Commander) Upload(upload proto.Commander_UploadServer) error { | ||
c.logger.Info("Commander Upload requested") | ||
|
||
for { | ||
chunk, err := upload.Recv() | ||
|
||
if err != nil && !errors.Is(err, io.EOF) { | ||
c.logger.Error(err, "upload receive error") | ||
return err | ||
} | ||
|
||
c.logger.Info("Received chunk from upload channel", "chunk", chunk) | ||
|
||
if errors.Is(err, io.EOF) { | ||
c.logger.Info("Commander Upload completed") | ||
return upload.SendAndClose(&proto.UploadStatus{Status: proto.UploadStatus_OK}) | ||
} | ||
} | ||
} | ||
|
||
func (c *Commander) handleReceive(server proto.Commander_CommandChannelServer) { | ||
for { | ||
cmd, err := server.Recv() | ||
if err != nil { | ||
c.logger.Error(err, "failed to receive command from CommandChannelServer") | ||
return | ||
} | ||
|
||
c.handleCommand(cmd) | ||
} | ||
} | ||
|
||
func (c *Commander) handleCommand(cmd *proto.Command) { | ||
if cmd != nil { | ||
switch commandData := cmd.Data.(type) { | ||
// The only command we care about right now is the AgentConnectRequest. | ||
case *proto.Command_AgentConnectRequest: | ||
c.logger.Info("Received a connection request from an agent", "data", commandData.AgentConnectRequest.GetMeta()) | ||
c.sendAgentConnectResponse(cmd) | ||
default: | ||
c.logger.Info("ignoring command", "command data type", fmt.Sprintf("%T", cmd.Data)) | ||
} | ||
} | ||
} | ||
|
||
func (c *Commander) sendAgentConnectResponse(cmd *proto.Command) { | ||
// get first nginx id for example | ||
nginxID := "0" | ||
if len(cmd.GetAgentConnectRequest().GetDetails()) > 0 { | ||
nginxID = cmd.GetAgentConnectRequest().GetDetails()[0].GetNginxId() | ||
} | ||
response := &proto.Command{ | ||
Data: &proto.Command_AgentConnectResponse{ | ||
AgentConnectResponse: &proto.AgentConnectResponse{ | ||
AgentConfig: &proto.AgentConfig{ | ||
Configs: &proto.ConfigReport{ | ||
Meta: grpc.NewMessageMeta(cmd.Meta.MessageId), | ||
Configs: []*proto.ConfigDescriptor{ | ||
{ | ||
Checksum: "", | ||
NginxId: nginxID, | ||
SystemId: cmd.GetAgentConnectRequest().GetMeta().GetSystemUid(), | ||
}, | ||
}, | ||
}, | ||
}, | ||
Status: &proto.AgentConnectStatus{ | ||
StatusCode: proto.AgentConnectStatus_CONNECT_OK, | ||
Message: "Connected", | ||
}, | ||
}, | ||
}, | ||
Meta: grpc.NewMessageMeta(cmd.Meta.MessageId), | ||
Type: proto.Command_NORMAL, | ||
} | ||
|
||
c.toClient <- response | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.