Skip to content

chore: Replaced all grpc.DialContext calls with dialContextBlocking #9013

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Kind can be one of:
# - breaking-change: a change to previously-documented behavior
# - deprecation: functionality that is being removed in a later release
# - bug-fix: fixes a problem in a previous version
# - enhancement: extends functionality but does not break or fix existing behavior
# - feature: new functionality
# - known-issue: problems that we are aware of in a given version
# - security: impacts on the security of a product or a user's deployment.
# - upgrade: important information for someone upgrading from a prior version
# - other: does not fit into any of the other categories
kind: enhancement

# Change summary; a 80ish characters long description of the change.
summary: Stop using deprecated grpc connection establishment functions

# Long description; in case the summary is not enough to describe the change
# this field accommodate a description without length limits.
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment.
description: |
Migrated from deprecated grpc.DialContext to grpc.NewClient while maintaining
blocking connection behavior. Created custom wrapper functions to preserve
the same functionality without using deprecated APIs.
# Affected component; usually one of "elastic-agent", "fleet-server", "filebeat", "metricbeat", "auditbeat", "all", etc.
component: "elastic-agent"

# PR URL; optional; the PR number that added the changeset.
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
# Please provide it if you are adding a fragment for a different PR.
#pr: https://github.com/elastic/elastic-agent/pull/XXXX

# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
# If not present is automatically filled by the tooling with the issue linked to the PR number.
issue: https://github.com/elastic/elastic-agent/issues/5453
37 changes: 37 additions & 0 deletions pkg/control/dial.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

package control

import (
"context"

"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)

// DialContextBlocking creates a blocking connection equivalent to the deprecated grpc.DialContext.
// It uses the new grpc.NewClient API but waits for the connection to be established before returning,
// maintaining the same blocking behavior as the deprecated function.
func DialContextBlocking(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
conn, err := grpc.NewClient(target, opts...)
if err != nil {
return nil, err
}

for {
state := conn.GetState()
if state == connectivity.Ready {
return conn, nil
}
if state == connectivity.TransientFailure || state == connectivity.Shutdown {
conn.Close()
return nil, ctx.Err()
}
if !conn.WaitForStateChange(ctx, state) {
conn.Close()
return nil, ctx.Err()
}
}
}
110 changes: 110 additions & 0 deletions pkg/control/dial_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.

package control

import (
"context"
"net"
"testing"
"time"

"google.golang.org/grpc"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
)

func TestDialContextBlocking_Success(t *testing.T) {
// Create a buffer connection for testing
buffer := bufconn.Listen(1024 * 1024)
defer buffer.Close()

// Start a mock gRPC server
server := grpc.NewServer()
go func() {
if err := server.Serve(buffer); err != nil {
t.Logf("Server serve error: %v", err)
}
}()
defer server.Stop()

// Test successful connection
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

conn, err := DialContextBlocking(ctx, "bufconn",
grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
return buffer.Dial()
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)

require.NoError(t, err, "DialContextBlocking failed")
defer conn.Close()

// Verify connection is ready
state := conn.GetState()
assert.Equal(t, connectivity.Ready, state, "Expected connection state to be Ready")
}

func TestDialContextBlocking_ContextCancellation(t *testing.T) {
// Create a context that cancels immediately
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately

// Try to establish connection with cancelled context
conn, err := DialContextBlocking(ctx, "unreachable:12345",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)

// Should return an error due to context cancellation
if err == nil {
conn.Close()
t.Fatal("Expected DialContextBlocking to fail with cancelled context")
}

if err != context.Canceled {
t.Errorf("Expected context.Canceled error, got %v", err)
}
}

func TestDialContextBlocking_InvalidTarget(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()

// Try to connect to an invalid target
conn, err := DialContextBlocking(ctx, "invalid-scheme://invalid-target",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)

// Should return an error
if err == nil {
conn.Close()
t.Fatal("Expected DialContextBlocking to fail with invalid target")
}
}

func TestDialContextBlocking_Timeout(t *testing.T) {
// Create a very short timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()

// Try to connect to a non-existent service
conn, err := DialContextBlocking(ctx, "127.0.0.1:1",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)

// Should return an error due to timeout
if err == nil {
conn.Close()
t.Fatal("Expected DialContextBlocking to fail with timeout")
}

if err != context.DeadlineExceeded {
t.Errorf("Expected context.DeadlineExceeded error, got %v", err)
}
}
2 changes: 1 addition & 1 deletion pkg/control/v1/client/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
)

func dialContext(ctx context.Context) (*grpc.ClientConn, error) {
return grpc.DialContext( //nolint:staticcheck // Only the deprecated version allows this call to be blocking
return control.DialContextBlocking(
ctx,
strings.TrimPrefix(control.Address(), "unix://"),
grpc.WithTransportCredentials(insecure.NewCredentials()),
Expand Down
2 changes: 1 addition & 1 deletion pkg/control/v1/client/dial_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
)

func dialContext(ctx context.Context) (*grpc.ClientConn, error) {
return grpc.DialContext( //nolint:staticcheck // Only the deprecated version allows this call to be blocking
return control.DialContextBlocking(
ctx,
control.Address(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
Expand Down
4 changes: 3 additions & 1 deletion pkg/control/v2/client/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"net"
"strings"

"github.com/elastic/elastic-agent/pkg/control"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
Expand All @@ -21,7 +23,7 @@ func dialContext(ctx context.Context, address string, maxMsgSize int, opts ...gr
grpc.WithContextDialer(dialer),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)),
)
return grpc.DialContext(ctx, address, opts...) //nolint:staticcheck // Only the deprecated version allows this call to be blocking
return control.DialContextBlocking(ctx, address, opts...)
}

func dialer(ctx context.Context, addr string) (net.Conn, error) {
Expand Down
4 changes: 3 additions & 1 deletion pkg/control/v2/client/dial_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"net"
"strings"

"github.com/elastic/elastic-agent/pkg/control"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

Expand All @@ -23,7 +25,7 @@ func dialContext(ctx context.Context, address string, maxMsgSize int, opts ...gr
grpc.WithContextDialer(dialer),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)),
)
return grpc.DialContext(ctx, address, opts...) //nolint:staticcheck // Only the deprecated version allows this call to be blocking
return control.DialContextBlocking(ctx, address, opts...)
}

func dialer(ctx context.Context, addr string) (net.Conn, error) {
Expand Down