This repository was archived by the owner on Aug 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
[DRAFT ]PMM-7000 Reconnect gRPC stream. #282
Draft
askomorokhov
wants to merge
2
commits into
main
Choose a base branch
from
PMM-7000-do-not-stop-agent-on-conn-fail-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,16 +17,21 @@ | |
| package channel | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
|
|
||
| "github.com/golang/protobuf/proto" //nolint:staticcheck | ||
| "github.com/percona/pmm/api/agentpb" | ||
| "github.com/pkg/errors" | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/sirupsen/logrus" | ||
| protostatus "google.golang.org/genproto/googleapis/rpc/status" | ||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/codes" | ||
| "google.golang.org/grpc/connectivity" | ||
| grpcstatus "google.golang.org/grpc/status" | ||
| ) | ||
|
|
||
|
|
@@ -64,8 +69,9 @@ type Response struct { | |
| // | ||
| // All exported methods are thread-safe. | ||
| type Channel struct { //nolint:maligned | ||
| s agentpb.Agent_ConnectClient | ||
| l *logrus.Entry | ||
| s agentpb.Agent_ConnectClient | ||
| l *logrus.Entry | ||
| MD *agentpb.ServerConnectMetadata | ||
|
|
||
| mRecv, mSend prometheus.Counter | ||
|
|
||
|
|
@@ -80,15 +86,46 @@ type Channel struct { //nolint:maligned | |
| closeOnce sync.Once | ||
| closeWait chan struct{} | ||
| closeErr error | ||
|
|
||
| reconnect chan bool | ||
| done chan bool | ||
| } | ||
|
|
||
| // New creates new two-way communication channel with given stream. | ||
| // | ||
| // Stream should not be used by the caller after channel is created. | ||
| func New(stream agentpb.Agent_ConnectClient) *Channel { | ||
| func New(conn *grpc.ClientConn, l *logrus.Entry, ID, version string) *Channel { | ||
| // gRPC stream is created without lifetime timeout. | ||
| // However, we need to cancel it if two-way communication channel can't be established | ||
| // when pmm-managed is down. A separate timer is used for that. | ||
| streamCtx, streamCancel := context.WithCancel(context.Background()) | ||
| l.Info("Establishing two-way communication channel ...") | ||
| streamCtx = agentpb.AddAgentConnectMetadata(streamCtx, &agentpb.AgentConnectMetadata{ | ||
| ID: ID, | ||
| Version: version, | ||
| }) | ||
|
|
||
| stream, err := agentpb.NewAgentClient(conn).Connect(streamCtx) | ||
| if err != nil { | ||
| l.Errorf("Failed to establish two-way communication channel: %s.", err) | ||
| streamCancel() | ||
| conn.Close() | ||
| return nil | ||
| } | ||
|
|
||
| md, err := agentpb.ReceiveServerConnectMetadata(stream) | ||
| l.Debugf("Received server metadata: %+v. Error: %+v.", md, err) | ||
| if err != nil { | ||
| l.Errorf("Failed to receive server metadata: %s.", err) | ||
| streamCancel() | ||
| conn.Close() | ||
| return nil | ||
| } | ||
|
|
||
| s := &Channel{ | ||
| s: stream, | ||
| l: logrus.WithField("component", "channel"), // only for debug logging | ||
| s: stream, | ||
| l: logrus.WithField("component", "channel"), // only for debug logging | ||
| MD: md, | ||
|
|
||
| mRecv: prometheus.NewCounter(prometheus.CounterOpts{ | ||
| Namespace: prometheusNamespace, | ||
|
|
@@ -106,13 +143,76 @@ func New(stream agentpb.Agent_ConnectClient) *Channel { | |
| responses: make(map[uint32]chan Response), | ||
| requests: make(chan *ServerRequest, serverRequestsCap), | ||
|
|
||
| reconnect: make(chan bool), | ||
| done: make(chan bool), | ||
|
|
||
| closeWait: make(chan struct{}), | ||
| } | ||
|
|
||
| go s.runReceiver() | ||
| go func() { | ||
| for { | ||
| select { | ||
| case <-s.reconnect: | ||
| if !s.waitUntilReady(conn, l) { | ||
| l.Errorf("Failed to establish two-way communication channel.") | ||
| } | ||
| streamCtx, streamCancel := context.WithCancel(context.Background()) | ||
| streamCtx = agentpb.AddAgentConnectMetadata(streamCtx, &agentpb.AgentConnectMetadata{ | ||
| ID: ID, | ||
| Version: version, | ||
| }) | ||
|
|
||
| stream, err := agentpb.NewAgentClient(conn).Connect(streamCtx) | ||
| if err != nil { | ||
| l.Errorf("Failed to establish two-way communication channel: %s.", err) | ||
| streamCancel() | ||
| conn.Close() | ||
| return | ||
| } | ||
| s.s = stream | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this replacement should be done more safety, it can cause race condition. |
||
| s.runReceiver() | ||
| // streamCancel() | ||
| case <-s.done: | ||
| l.Infoln("Done.") | ||
| streamCancel() | ||
| close(s.requests) | ||
| return | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| return s | ||
| } | ||
|
|
||
| // waitUntilReady implements queues the RPCs until the channel is READY | ||
| // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md | ||
| func (c *Channel) waitUntilReady(conn *grpc.ClientConn, l *logrus.Entry) bool { | ||
| //define how long you want to wait for connection to be restored before giving up | ||
| ctx, cancel := context.WithTimeout(context.Background(), 720*time.Hour) // 30 days | ||
| defer cancel() | ||
|
|
||
| currentState := conn.GetState() | ||
| stillConnecting := true | ||
|
|
||
| for currentState != connectivity.Ready && stillConnecting { | ||
| if currentState == connectivity.Shutdown { // pmm-server was shutted down | ||
| c.done <- true | ||
| return false | ||
| } | ||
| //will return true when state has changed from thisState, false if timeout | ||
| stillConnecting = conn.WaitForStateChange(ctx, currentState) | ||
| currentState = conn.GetState() | ||
| } | ||
|
|
||
| if stillConnecting == false { | ||
| l.Error("Connection attempt has timed out.") | ||
| return false | ||
| } | ||
|
|
||
| return true | ||
| } | ||
|
|
||
| // close marks channel as closed with given error - only once. | ||
| func (c *Channel) close(err error) { | ||
| c.closeOnce.Do(func() { | ||
|
|
@@ -205,16 +305,20 @@ func (c *Channel) send(msg *agentpb.AgentMessage) { | |
| // runReader receives messages from server | ||
| func (c *Channel) runReceiver() { | ||
| defer func() { | ||
| close(c.requests) | ||
| c.l.Debug("Exiting receiver goroutine.") | ||
| }() | ||
|
|
||
| for { | ||
| msg, err := c.s.Recv() | ||
| if err != nil { | ||
| if err == io.EOF { | ||
| c.done <- true | ||
| c.close(errors.Wrap(err, "failed to receive message")) | ||
| return | ||
| } | ||
| if err != nil { | ||
| c.reconnect <- true | ||
| return | ||
| } | ||
| c.mRecv.Inc() | ||
|
|
||
| // do not use default compact representation for large/complex messages | ||
|
|
||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this doesn't override streamCancel, so https://github.com/percona/pmm-agent/pull/282/files#diff-181c0efbb5b86fbcca31d699687ecec527e9818a5835bfe36cac81f691604392R178 will cancel another stream.