-
Notifications
You must be signed in to change notification settings - Fork 485
feat(grpc): add healthz support #5218
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
Draft
josedonizetti
wants to merge
1
commit into
aquasecurity:main
Choose a base branch
from
josedonizetti:add-grpc-healthz
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
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
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,65 @@ | ||
| package grpc | ||
|
|
||
| import ( | ||
| "context" | ||
| "time" | ||
|
|
||
| "google.golang.org/grpc/health" | ||
| healthpb "google.golang.org/grpc/health/grpc_health_v1" | ||
|
|
||
| "github.com/aquasecurity/tracee/pkg/ebpf/heartbeat" | ||
| ) | ||
|
|
||
| // HealthService wraps the standard gRPC health server and integrates with Tracee's heartbeat mechanism | ||
| type HealthService struct { | ||
| server *health.Server | ||
| } | ||
|
|
||
| // NewHealthService creates a new HealthService instance | ||
| func NewHealthService() *HealthService { | ||
| return &HealthService{ | ||
| server: health.NewServer(), | ||
| } | ||
| } | ||
|
|
||
| // Server returns the underlying health server for registration | ||
| func (h *HealthService) Server() *health.Server { | ||
| return h.server | ||
| } | ||
|
|
||
| // StartMonitor polls heartbeat status and updates gRPC health accordingly. | ||
| // It monitors the heartbeat at regular intervals and updates the health status | ||
| // for all registered services based on whether the heartbeat is alive. | ||
| func (h *HealthService) StartMonitor(ctx context.Context) { | ||
| // Use empty string for overall server health | ||
| // This is sufficient for Kubernetes gRPC probes and most health checking scenarios | ||
| // Individual service health can be added later if needed | ||
| overallService := "" | ||
|
|
||
| // Initialize overall health as NOT_SERVING until heartbeat confirms health | ||
| h.server.SetServingStatus(overallService, healthpb.HealthCheckResponse_NOT_SERVING) | ||
|
|
||
| // Poll at the same interval as the heartbeat ack timeout (2s), since that's | ||
| // the boundary at which IsAlive() state actually changes. | ||
| ticker := time.NewTicker(2 * time.Second) | ||
| defer ticker.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| // Set overall health to NOT_SERVING on shutdown | ||
| h.server.SetServingStatus(overallService, healthpb.HealthCheckResponse_NOT_SERVING) | ||
| return | ||
| case <-ticker.C: | ||
| // Poll heartbeat status | ||
| instance := heartbeat.GetInstance() | ||
| status := healthpb.HealthCheckResponse_NOT_SERVING | ||
| if instance != nil && instance.IsAlive() { | ||
| status = healthpb.HealthCheckResponse_SERVING | ||
| } | ||
|
|
||
| // Update overall health status | ||
| h.server.SetServingStatus(overallService, status) | ||
| } | ||
| } | ||
| } |
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,98 @@ | ||
| package grpc | ||
|
|
||
| import ( | ||
| "context" | ||
| "os" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "google.golang.org/grpc" | ||
| "google.golang.org/grpc/credentials/insecure" | ||
| healthpb "google.golang.org/grpc/health/grpc_health_v1" | ||
|
|
||
| "github.com/aquasecurity/tracee/pkg/ebpf/heartbeat" | ||
| "github.com/aquasecurity/tracee/pkg/server" | ||
| ) | ||
|
|
||
| func TestHealthService_Check(t *testing.T) { | ||
| tempDir, err := os.MkdirTemp("", "tracee-health-tests") | ||
| require.NoError(t, err) | ||
| defer os.RemoveAll(tempDir) | ||
|
|
||
| unixSock := tempDir + "/tracee.sock" | ||
| defer os.Remove(unixSock) | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| // Don't cancel context until test is done to avoid closing heartbeat | ||
| defer cancel() | ||
|
|
||
| // Initialize heartbeat for testing | ||
| // Use a background context that won't be cancelled to keep heartbeat alive | ||
| bgCtx := context.Background() | ||
| heartbeat.Init(bgCtx, 1*time.Second, 2*time.Second) | ||
| instance := heartbeat.GetInstance() | ||
| require.NotNil(t, instance) | ||
| instance.SetCallback(server.InvokeHeartbeat) | ||
| instance.Start() | ||
|
|
||
| // In tests, manually send pulses since uprobe isn't attached | ||
| pulseCtx, pulseCancel := context.WithCancel(ctx) | ||
| defer pulseCancel() | ||
| go func() { | ||
| ticker := time.NewTicker(500 * time.Millisecond) | ||
| defer ticker.Stop() | ||
| for { | ||
| select { | ||
| case <-ticker.C: | ||
| safeSendPulse() | ||
| case <-pulseCtx.Done(): | ||
| return | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| grpcServer := New("unix", unixSock) | ||
| grpcServer.EnableHealthService() | ||
| go grpcServer.Start(ctx, nil, nil) | ||
|
|
||
| // Wait for server to start | ||
| require.Eventually(t, func() bool { | ||
| _, err := os.Stat(unixSock) | ||
| return err == nil | ||
| }, 2*time.Second, 10*time.Millisecond) | ||
|
|
||
| // Create health client | ||
| conn, err := grpc.NewClient("unix:"+unixSock, grpc.WithTransportCredentials(insecure.NewCredentials())) | ||
| require.NoError(t, err) | ||
| defer conn.Close() | ||
|
|
||
| healthClient := healthpb.NewHealthClient(conn) | ||
|
|
||
| // Send initial pulse immediately | ||
| safeSendPulse() | ||
|
|
||
| // Wait for health service monitor to poll and update status (polls every 2s) | ||
| require.Eventually(t, func() bool { | ||
| resp, err := healthClient.Check(ctx, &healthpb.HealthCheckRequest{}) | ||
| return err == nil && resp.Status == healthpb.HealthCheckResponse_SERVING | ||
| }, 5*time.Second, 100*time.Millisecond, "health service should become SERVING") | ||
|
|
||
| // Test overall health (empty service name) | ||
| t.Run("overall health check", func(t *testing.T) { | ||
| resp, err := healthClient.Check(ctx, &healthpb.HealthCheckRequest{}) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, healthpb.HealthCheckResponse_SERVING, resp.Status) | ||
| }) | ||
| } | ||
|
|
||
| // safeSendPulse safely sends a pulse, recovering from panics if the channel is closed or instance is nil | ||
| func safeSendPulse() { | ||
| defer func() { | ||
| recover() | ||
| }() | ||
| if instance := heartbeat.GetInstance(); instance != nil { | ||
| heartbeat.SendPulse() | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package server | ||
|
|
||
| // InvokeHeartbeat is a no-op function used as a callback for heartbeat. | ||
| // It's instrumented by an uprobe to detect liveness. | ||
| // This function is shared between HTTP and gRPC servers. | ||
| // | ||
| //go:noinline | ||
| func InvokeHeartbeat() { | ||
| // Intentionally left empty | ||
| } | ||
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
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.
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.
Just a doubt, this go routine spawning could race with the line 84 somehow (inside other spawning)?
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.
No race here. The
RegisterHealthServercall on line 78 completes synchronously before either goroutine is spawned. After that, the two goroutines operate on independent concerns:StartMonitoronly callshealth.Server.SetServingStatus(), which is internally synchronized with a mutex in the standard gRPC health server implementation.grpcServer.Serve()starts accepting connections and dispatching RPCs, reading the health status through the same mutex-protectedCheck/Watchhandlers.So even if
Servestarts accepting connections beforeStartMonitorsets the initialNOT_SERVINGstatus, a health check arriving in that window would getSERVICE_UNKNOWN(the default for unregistered services), which Kubernetes treats as unhealthy — same practical effect asNOT_SERVING.