Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
48 changes: 28 additions & 20 deletions pkg/operator/encryption/kms/health/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import (
"regexp"
"time"

"github.com/openshift/library-go/pkg/operator/v1helpers"
"github.com/spf13/cobra"
"github.com/spf13/pflag"

metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/server"
k8senvelopekmsv2 "k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
)

const Subcommand = "kms-health-reporter"
const (
Subcommand = "kms-health-reporter"
)

// kmsSocketPattern matches the socket path each co-located KMSv2 plugin is
// mounted at, e.g. unix:///var/run/kmsplugin/kms-1.sock.
Expand All @@ -35,21 +36,20 @@ type options struct {
NodeName string
Kubeconfig string

newOperatorClient func(*rest.Config) (v1helpers.OperatorClient, error)
newWriter NewEncryptionStatusWriterFunc
Comment thread
ibihim marked this conversation as resolved.
Resolved
}

type Config struct {
operatorClient v1helpers.OperatorClient
prober *prober
writeStatus EncryptionStatusWriter
prober *prober

interval time.Duration
writeTimeout time.Duration
nodeName string
}

func NewCommand(ctx context.Context, newOperatorClient func(*rest.Config) (v1helpers.OperatorClient, error)) *cobra.Command {
func NewCommand(ctx context.Context, newWriter NewEncryptionStatusWriterFunc) *cobra.Command {
o := &options{
newOperatorClient: newOperatorClient,
newWriter: newWriter,
}

cmd := &cobra.Command{
Expand Down Expand Up @@ -114,6 +114,9 @@ func (o *options) validate() error {
if o.NodeName == "" {
return fmt.Errorf("--node-name is required")
}
if fieldManager := fmt.Sprintf("%s-%s", Subcommand, o.NodeName); len(fieldManager) > metav1validation.FieldManagerMaxLength {
return fmt.Errorf("--node-name too long: reporter identity %q is %d chars, exceeds the %d-char fieldManager limit", fieldManager, len(fieldManager), metav1validation.FieldManagerMaxLength)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we really hit this error?.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how would you even get out of this situation as an admin? rename your nodes?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with the prefix we have like 100 characters left, I think it's OK. We can also make the prefix a bit shorter?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can just continue as is and allow kube-apiserver errors out?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think he has a case with this, but we probably need a different solution here

checkout the max length we can have per node:
https://github.com/kubernetes/apimachinery/blob/master/pkg/api/validate/content/dns.go#L56-L57

@ardaguclu ardaguclu Jun 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with Thomas. If it is possible, maybe we can use something else (uuid, hash, etc.) to remove that check. I think, other than this thread, this PR is ready to merge.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can do that as a follow-up. This is probably a bit bigger because we have to rename the cmdline and add this in the lifecycle

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about cutting the static length from node name, if it exceeds?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you'd have to cut the unique bits from the back and hope they don't have a subdomain per node, as Krzys says

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. Thank you

}

return nil
}
Expand All @@ -126,9 +129,11 @@ func (o *options) Config(ctx context.Context) (*Config, error) {
return nil, fmt.Errorf("build rest config: %w", err)
}

operatorClient, err := o.newOperatorClient(restCfg)
// fieldManager is the per-node ownership identity.
fieldManager := fmt.Sprintf("%s-%s", Subcommand, o.NodeName)
writeStatus, err := o.newWriter(restCfg, fieldManager)
if err != nil {
return nil, fmt.Errorf("build operator client: %w", err)
return nil, fmt.Errorf("build encryption status writer: %w", err)
}

plugins, err := buildPlugins(ctx, o.KMSSockets, o.ReadTimeout)
Expand All @@ -137,21 +142,24 @@ func (o *options) Config(ctx context.Context) (*Config, error) {
}

return &Config{
operatorClient: operatorClient,
prober: newProber(plugins),
interval: o.Interval,
writeTimeout: o.WriteTimeout,
nodeName: o.NodeName,
writeStatus: writeStatus,
prober: newProber(o.NodeName, plugins),
interval: o.Interval,
writeTimeout: o.WriteTimeout,
}, nil
}

func (c *Config) Run(ctx context.Context) error {
wait.JitterUntilWithContext(ctx, func(ctx context.Context) {
// Each Status RPC enforces the read timeout internally (set at dial
// time); ctx here only carries shutdown cancellation.
conditions := c.prober.probeAll(ctx)
// TODO: hand conditions to the writer once it lands; logging is a placeholder.
klog.InfoS("kms plugin health", "conditions", conditions)
reports := c.prober.probeAll(ctx)

writeCtx, cancel := context.WithTimeout(ctx, c.writeTimeout)
defer cancel()
if err := c.writeStatus(writeCtx, reports); err != nil {
klog.ErrorS(err, "failed to publish kms plugin health")
}
}, c.interval, 0.1, false)

return nil
Expand All @@ -168,7 +176,7 @@ func buildPlugins(ctx context.Context, sockets []string, timeout time.Duration)

// Unique name per plugin so the gRPC client's KMS operation metrics
// don't merge both plugins into one series.
service, err := k8senvelopekmsv2.NewGRPCService(ctx, socket, Subcommand+"-"+keyID, timeout)
service, err := k8senvelopekmsv2.NewGRPCService(ctx, socket, Subcommand, timeout)
if err != nil {
// With the current dependency version this should never happen with a validated GRPC endpoint.
return nil, fmt.Errorf("setting up grpc service failed at %q: %w", socket, err)
Expand Down
45 changes: 45 additions & 0 deletions pkg/operator/encryption/kms/health/cmd_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package health

import (
"context"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"

applyoperatorv1 "github.com/openshift/client-go/operator/applyconfigurations/operator/v1"
kmsservice "k8s.io/kms/pkg/service"
)

// validOptions returns an options value that passes validate. Each test case
Expand Down Expand Up @@ -103,6 +108,15 @@ func TestValidate(t *testing.T) {
mutate: func(o *options) { o.NodeName = "" },
wantErr: true,
},
{
name: "node name at fieldManager limit",
mutate: func(o *options) { o.NodeName = strings.Repeat("n", 108) }, // 20-char prefix + 108 == 128
},
{
name: "node name over fieldManager limit",
mutate: func(o *options) { o.NodeName = strings.Repeat("n", 109) }, // 20-char prefix + 109 > 128
wantErr: true,
},
}

for _, tc := range tests {
Expand All @@ -119,3 +133,34 @@ func TestValidate(t *testing.T) {
})
}
}

// TestRunReportsOnce checks the loop wiring: Run probes, builds the status, and
// hands it to the reporter. The reporter cancels the context so the loop ends
// after a single tick.
func TestRunReportsOnce(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
t.Cleanup(cancel)

var have *applyoperatorv1.KMSEncryptionStatusApplyConfiguration
c := &Config{
interval: time.Hour, // never reached; cancelled after the first tick
writeTimeout: time.Second,
prober: &prober{
nodeName: "node-1",
plugins: []pluginClient{
{keyID: "1", service: &fakeService{resp: &kmsservice.StatusResponse{Healthz: "ok", KeyID: "kek-abc"}}},
},
now: func() time.Time { return time.Unix(0, 0).UTC() },
},
writeStatus: func(_ context.Context, status *applyoperatorv1.KMSEncryptionStatusApplyConfiguration) error {
have = status
cancel()
return nil
},
}

require.NoError(t, c.Run(ctx))
require.Len(t, have.HealthReports, 1)
require.Equal(t, "node-1", *have.HealthReports[0].NodeName)
require.Equal(t, "1", *have.HealthReports[0].KeyId)
}
65 changes: 29 additions & 36 deletions pkg/operator/encryption/kms/health/prober.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,22 @@ package health

import (
"context"
"errors"
"sync"
"time"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kmsservice "k8s.io/kms/pkg/service"

operatorv1 "github.com/openshift/api/operator/v1"
applyoperatorv1 "github.com/openshift/client-go/operator/applyconfigurations/operator/v1"
)

// healthzOK is the value the KMS plugin returns when healthy.
// See https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/kms/apis/v2/api.proto#L39
const healthzOK = "ok"

const (
statusHealthy = "healthy"
statusUnhealthy = "unhealthy"
statusError = "error"
)

type pluginHealthReport struct {
// KeyID is the controller's sequential key id; KEKID is the KMS provider's
// encryption key id. Distinct identifiers, easy to confuse.
KeyID string
KEKID string
Status string
LastChecked time.Time
Detail string
}
var errResponseless error = errors.New("kms plugin returned nil status response")

// pluginClient is the dialed handle to one co-located KMS plugin; the plugin
// itself is a separate process behind the unix socket.
Expand All @@ -36,23 +27,25 @@ type pluginClient struct {
}

type prober struct {
plugins []pluginClient
now func() time.Time
nodeName string
plugins []pluginClient
now func() time.Time
}

func newProber(plugins []pluginClient) *prober {
func newProber(nodeName string, plugins []pluginClient) *prober {
return &prober{
plugins: plugins,
now: time.Now,
nodeName: nodeName,
plugins: plugins,
now: time.Now,
}
}

// probeAll never returns an error: a failed probe is encoded as a report
// with Status "error" so the caller always gets one entry per plugin.
// Probes run concurrently so one hung plugin doesn't delay the others;
// worst-case duration is one read-timeout, not the sum.
func (p *prober) probeAll(ctx context.Context) []pluginHealthReport {
reports := make([]pluginHealthReport, len(p.plugins))
func (p *prober) probeAll(ctx context.Context) *applyoperatorv1.KMSEncryptionStatusApplyConfiguration {
reports := make([]*applyoperatorv1.KMSPluginHealthReportApplyConfiguration, len(p.plugins))

var wg sync.WaitGroup
for i, plugin := range p.plugins {
Expand All @@ -62,31 +55,31 @@ func (p *prober) probeAll(ctx context.Context) []pluginHealthReport {
}
wg.Wait()

return reports
return applyoperatorv1.KMSEncryptionStatus().WithHealthReports(reports...)
}

func (p *prober) probe(ctx context.Context, plugin pluginClient) pluginHealthReport {
report := pluginHealthReport{
KeyID: plugin.keyID,
LastChecked: p.now(),
}
func (p *prober) probe(ctx context.Context, plugin pluginClient) *applyoperatorv1.KMSPluginHealthReportApplyConfiguration {
report := applyoperatorv1.KMSPluginHealthReport().
WithNodeName(p.nodeName).
WithKeyId(plugin.keyID).
WithLastCheckedTime(metav1.NewTime(p.now()))

resp, err := plugin.service.Status(ctx)
switch {
case err != nil:
report.Status = statusError
report.Detail = err.Error()
report.WithStatus(operatorv1.KMSPluginHealthStatusError).
WithDetail(err.Error())
case resp == nil:
// The in-tree gRPC client never returns (nil, nil), but a misbehaving
// plugin must not panic the reporter.
report.Status = statusError
report.Detail = "kms plugin returned nil status response"
report.WithStatus(operatorv1.KMSPluginHealthStatusError).
WithDetail(errResponseless.Error())
case resp.Healthz == healthzOK:
report.Status = statusHealthy
report.KEKID = resp.KeyID
report.WithStatus(operatorv1.KMSPluginHealthStatusHealthy).
WithKEKId(resp.KeyID)
default:
report.Status = statusUnhealthy
report.Detail = resp.Healthz
report.WithStatus(operatorv1.KMSPluginHealthStatusUnhealthy).
WithDetail(resp.Healthz)
}

return report
Expand Down
Loading