Skip to content
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

Elastic Agent: Set status.ObservedGeneration from metadata.Generation #5383

Merged
merged 35 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
fd34d3d
Add agent observed generation.
naemono Feb 7, 2022
5bc9db5
Run generation and update yaml for observedGeneration description cha…
naemono Feb 15, 2022
8b7e14a
Properly order imports
naemono Feb 15, 2022
9de32ab
capitalize Agent
naemono Feb 15, 2022
f77b470
remove erroneous debugging line
naemono Feb 15, 2022
30f6c8f
renamed agent e2e test file.
naemono Feb 15, 2022
c6661bb
Ignore generation when checking if agent status is updated during k8s…
naemono Feb 16, 2022
58ed712
remove unneeded nil in return from rebase.
naemono Feb 16, 2022
b6045d0
Add missing header to e2e test.
naemono Feb 16, 2022
1374e88
Remove unused args struct
naemono Feb 16, 2022
5e03689
move imports around properly
naemono Feb 16, 2022
b96cd85
Defer agent validation to reduce repetitive code.
naemono Feb 21, 2022
2bc4fd9
Updating metav1.Object -> client.Object, and using type switch to get…
naemono Feb 22, 2022
a58c2da
Allow status to be updated even if associations are broken.
naemono Mar 9, 2022
250fcb5
Allow error to be returned from doReconcile during defer.
naemono Mar 9, 2022
a78d66d
Merge branch 'main' into 3392-agent-observedGeneration
naemono Mar 9, 2022
27027d0
Merge branch 'main' of https://github.com/elastic/cloud-on-k8s into 3…
naemono Mar 10, 2022
8b549f8
ensure withmutatedfrom is used in e2e agent tests.
naemono Mar 10, 2022
28731f7
Ensure we're not returning nil results
naemono Mar 10, 2022
ea5935e
Fixing comparison issues from rebase/merge
naemono Mar 10, 2022
c10da1b
Add nolint for the naked return, which is required for the defer to f…
naemono Mar 10, 2022
3d9975d
Handle updating status properly when associations are broken.
naemono Mar 10, 2022
bc4f919
Debugging
naemono Mar 10, 2022
ecad6df
Debugging, and moving the defer
naemono Mar 10, 2022
4c8d2ec
Go back to previous way of handling fetch association errors
naemono Mar 10, 2022
d7844d7
remove extraneous logging statement
naemono Mar 10, 2022
205b1cf
Move status update to calling function.
naemono Mar 17, 2022
5177545
Remove unused context
naemono Mar 18, 2022
b850b4f
Update the func's comments to be consistent
naemono Mar 21, 2022
4e6f801
remove unneeded return
naemono Mar 21, 2022
f782303
Merge branch 'main' into 3392-agent-observedGeneration
naemono Mar 24, 2022
0dea707
move common.LowestVersionFromPods closer to where pods are retrieved.
naemono Mar 31, 2022
074933c
changes to return status instead of modifying a pointer.
naemono Mar 31, 2022
2894c06
rename variable
naemono Mar 31, 2022
052fb3f
Updating how status is handled for consistency
naemono Apr 4, 2022
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
9 changes: 9 additions & 0 deletions config/crds/v1/all-crds.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,15 @@ spec:
kibanaAssociationStatus:
description: AssociationStatus is the status of an association resource.
type: string
observedGeneration:
description: ObservedGeneration is the most recent generation observed
for this Elastic Agent. It corresponds to the metadata generation,
which is updated on mutation by the API Server. If the generation
observed in status diverges from the generation in metadata, the
Elastic Agent controller has not yet processed the changes contained
in the Elastic Agent specification.
format: int64
type: integer
version:
description: 'Version of the stack resource currently running. During
version upgrades, multiple versions may run in parallel: this value
Expand Down
9 changes: 9 additions & 0 deletions config/crds/v1/bases/agent.k8s.elastic.co_agents.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15630,6 +15630,15 @@ spec:
kibanaAssociationStatus:
description: AssociationStatus is the status of an association resource.
type: string
observedGeneration:
description: ObservedGeneration is the most recent generation observed
for this Elastic Agent. It corresponds to the metadata generation,
which is updated on mutation by the API Server. If the generation
observed in status diverges from the generation in metadata, the
Elastic Agent controller has not yet processed the changes contained
in the Elastic Agent specification.
format: int64
type: integer
version:
description: 'Version of the stack resource currently running. During
version upgrades, multiple versions may run in parallel: this value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,15 @@ spec:
kibanaAssociationStatus:
description: AssociationStatus is the status of an association resource.
type: string
observedGeneration:
description: ObservedGeneration is the most recent generation observed
for this Elastic Agent. It corresponds to the metadata generation,
which is updated on mutation by the API Server. If the generation
observed in status diverges from the generation in metadata, the
Elastic Agent controller has not yet processed the changes contained
in the Elastic Agent specification.
format: int64
type: integer
version:
description: 'Version of the stack resource currently running. During
version upgrades, multiple versions may run in parallel: this value
Expand Down
11 changes: 11 additions & 0 deletions pkg/apis/agent/v1alpha1/agent_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ type AgentStatus struct {

// +kubebuilder:validation:Optional
FleetServerAssociationStatus commonv1.AssociationStatus `json:"fleetServerAssociationStatus,omitempty"`

// ObservedGeneration is the most recent generation observed for this Elastic Agent.
// It corresponds to the metadata generation, which is updated on mutation by the API Server.
// If the generation observed in status diverges from the generation in metadata, the Elastic
// Agent controller has not yet processed the changes contained in the Elastic Agent specification.
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
}

type AgentHealth string
Expand Down Expand Up @@ -282,6 +288,11 @@ func (a *Agent) SecureSettings() []commonv1.SecretSource {
return a.Spec.SecureSettings
}

// GetObservedGeneration will return the observedGeneration from the Elastic Agent's status.
func (a *Agent) GetObservedGeneration() int64 {
return a.Status.ObservedGeneration
}

type AgentESAssociation struct {
*Agent
// ref is the namespaced name of the Elasticsearch used in Association
Expand Down
45 changes: 31 additions & 14 deletions pkg/controller/agent/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,21 +121,24 @@ type ReconcileAgent struct {

// Reconcile reads that state of the cluster for an Agent object and makes changes based on the state read
// and what is in the Agent.Spec
func (r *ReconcileAgent) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
func (r *ReconcileAgent) Reconcile(ctx context.Context, request reconcile.Request) (result reconcile.Result, err error) {
naemono marked this conversation as resolved.
Show resolved Hide resolved
ctx = common.NewReconciliationContext(ctx, &r.iteration, r.Tracer, controllerName, "agent_name", request)
defer common.LogReconciliationRunNoSideEffects(logconf.FromContext(ctx))()
defer tracing.EndContextTransaction(ctx)

var agent agentv1alpha1.Agent
if err := association.FetchWithAssociations(ctx, r.Client, request, &agent); err != nil {
agent := &agentv1alpha1.Agent{}
if err = association.FetchWithAssociations(ctx, r.Client, request, agent); err != nil {
if apierrors.IsNotFound(err) {
r.onDelete(request.NamespacedName)
return reconcile.Result{}, nil
}
return reconcile.Result{}, tracing.CaptureError(ctx, err)
if agent == nil {
return reconcile.Result{}, err
}
return updateStatus(ctx, *agent, r.Client, newStatus(*agent)).WithError(err).Aggregate()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Which case are we covering here? If we cannot fetch the Agent resource we cannot update. The case where we can fetch the Agent resource but the JSON in the association config is invalid is the only one I can think of. We do not handle this case for the Kibana resource as far as I can tell. I think it would be good to be somewhat consistent here.

So assuming I am not missing an obvious case (totally possible), I am not fully decided which way we should go here. Either we consider this case too much of an edge case to warrant updating the status in two places (which I would be OK with at this point) or we try to bring all the status update functionality into the same place.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've just removed updating the status on association failures, as it seems to be causing more issues than it's worth.

}

if common.IsUnmanaged(&agent) {
if common.IsUnmanaged(agent) {
logconf.FromContext(ctx).Info("Object is currently not managed by this controller. Skipping reconciliation")
return reconcile.Result{}, nil
}
Expand All @@ -144,22 +147,35 @@ func (r *ReconcileAgent) Reconcile(ctx context.Context, request reconcile.Reques
return reconcile.Result{}, nil
}

res, err := r.doReconcile(ctx, agent).Aggregate()
k8s.EmitErrorEvent(r.recorder, err, &agent, events.EventReconciliationError, "Reconciliation error: %v", err)
result, err = r.doReconcile(ctx, *agent).Aggregate()
k8s.EmitErrorEvent(r.recorder, err, agent, events.EventReconciliationError, "Reconciliation error: %v", err)

return res, err
return result, err
}

func (r *ReconcileAgent) doReconcile(ctx context.Context, agent agentv1alpha1.Agent) *reconciler.Results {
func (r *ReconcileAgent) doReconcile(ctx context.Context, agent agentv1alpha1.Agent) (results *reconciler.Results) {
defer tracing.Span(&ctx)()
results := reconciler.NewResult(ctx)
var err error
naemono marked this conversation as resolved.
Show resolved Hide resolved
results = reconciler.NewResult(ctx)
status := newStatus(agent)

// defer the updating of status to ensure that the status is updated regardless of the outcome of the reconciliation.
// note that this deferred function is modifying the return values, which are named return values, which allows this
// to function properly.
defer func() {
if updateStatusresults := updateStatus(ctx, agent, r.Client, status).WithError(err); updateStatusresults != nil {
naemono marked this conversation as resolved.
Show resolved Hide resolved
results = updateStatusresults
}
}()

if !association.AreConfiguredIfSet(agent.GetAssociations(), r.recorder) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think observedGeneration should be updated even if associations are not correctly set. One reason is that misconfigured associations are not immediately detected. Here is an example:

  1. Deploy config/recipes/elastic-agent/fleet-kubernetes-integration.yaml
  2. observerdGeneration is eventually updated:
 k get agent.agent.k8s.elastic.co/fleet-server -o go-template='{{ printf "\nGeneration: "}}{{.metadata.generation}}{{printf "\n\nStatus:"}}{{.status}}'

Generation: 2

Status:map[availableNodes:1 elasticsearchAssociationsStatus:map[default/elasticsearch:Established] expectedNodes:1 health:green kibanaAssociationStatus:Established observedGeneration:2 version:8.0.0]

⬆️ generation and observedGeneration are both set to 2

  1. Break one of the association, for example Kibana, observedGeneration is still updated:

Generation: 3

Status:map[availableNodes:1 elasticsearchAssociationsStatus:map[default/elasticsearch:Established] expectedNodes:1 health:green kibanaAssociationStatus:Pending observedGeneration:3 version:8.0.0

⬆️ generation and observedGeneration are both set to 3

  1. Update the Agent resource while keeping the Kibana association broken, observedGeneration is no more updated, which seems a bit confusing to me and does not match the description "If the generation observed in status diverges from the generation in metadata, the Elastic Agent controller has not yet processed the changes contained in the Elastic Agent specification."
k get agent.agent.k8s.elastic.co/fleet-server -o go-template='{{ printf "\nGeneration: "}}{{.metadata.generation}}{{printf "\n\nStatus:"}}{{.status}}'

Generation: 4

Status:map[availableNodes:1 elasticsearchAssociationsStatus:map[default/elasticsearch:Established] expectedNodes:1 health:green kibanaAssociationStatus:Pending observedGeneration:3 version:8.0.0]

⬆️ generation has been updated to 4, but observedGeneration is still 3

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This logic has been updated, and I'll get these steps tested.

return results
}

// Run basic validations as a fallback in case webhook is disabled.
if err := r.validate(ctx, agent); err != nil {
return results.WithError(err)
if err = r.validate(ctx, agent); err != nil {
results = results.WithError(err)
return results
naemono marked this conversation as resolved.
Show resolved Hide resolved
}

driverResults := internalReconcile(Params{
Expand All @@ -169,9 +185,10 @@ func (r *ReconcileAgent) doReconcile(ctx context.Context, agent agentv1alpha1.Ag
Watches: r.dynamicWatches,
Agent: agent,
OperatorParams: r.Parameters,
})
}, &status)

return results.WithResults(driverResults)
results = results.WithResults(driverResults)
return results
naemono marked this conversation as resolved.
Show resolved Hide resolved
}

func (r *ReconcileAgent) validate(ctx context.Context, agent agentv1alpha1.Agent) error {
Expand Down
144 changes: 144 additions & 0 deletions pkg/controller/agent/controller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// 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 agent

import (
"context"
"reflect"
"testing"

"github.com/google/go-cmp/cmp"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/reconcile"

agentv1alpha1 "github.com/elastic/cloud-on-k8s/pkg/apis/agent/v1alpha1"
"github.com/elastic/cloud-on-k8s/pkg/controller/common"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/comparison"
"github.com/elastic/cloud-on-k8s/pkg/utils/k8s"
)

func newReconcileAgent(objs ...runtime.Object) *ReconcileAgent {
Copy link
Collaborator

Choose a reason for hiding this comment

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

You are using this in only one place you might as well inline it. But its fine if you want to keep it.

r := &ReconcileAgent{
Client: k8s.NewFakeClient(objs...),
recorder: record.NewFakeRecorder(100),
}
return r
}

func TestReconcileAgent_Reconcile(t *testing.T) {
tests := []struct {
name string
objs []runtime.Object
request reconcile.Request
want reconcile.Result
expected agentv1alpha1.Agent
wantErr bool
}{
{
name: "valid unmanaged agent does not increment observedGeneration",
objs: []runtime.Object{
&agentv1alpha1.Agent{
ObjectMeta: metav1.ObjectMeta{
Name: "testAgent",
Namespace: "test",
Generation: 1,
Annotations: map[string]string{
common.ManagedAnnotation: "false",
},
},
Spec: agentv1alpha1.AgentSpec{
Version: "8.0.1",
Deployment: &agentv1alpha1.DeploymentSpec{},
},
Status: agentv1alpha1.AgentStatus{
ObservedGeneration: 1,
},
},
},
request: reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: "test",
Name: "testAgent",
},
},
want: reconcile.Result{},
expected: agentv1alpha1.Agent{
ObjectMeta: metav1.ObjectMeta{
Name: "testAgent",
Namespace: "test",
Generation: 1,
Annotations: map[string]string{
common.ManagedAnnotation: "false",
},
},
Spec: agentv1alpha1.AgentSpec{
Version: "8.0.1",
Deployment: &agentv1alpha1.DeploymentSpec{},
},
Status: agentv1alpha1.AgentStatus{
ObservedGeneration: 1,
},
},
wantErr: false,
},
{
name: "too long name fails validation, and updates observedGeneration",
objs: []runtime.Object{
&agentv1alpha1.Agent{
ObjectMeta: metav1.ObjectMeta{
Name: "testAgentwithtoolongofanamereallylongname",
Namespace: "test",
Generation: 2,
},
Status: agentv1alpha1.AgentStatus{
ObservedGeneration: 1,
},
},
},
request: reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: "test",
Name: "testAgentwithtoolongofanamereallylongname",
},
},
want: reconcile.Result{},
expected: agentv1alpha1.Agent{
ObjectMeta: metav1.ObjectMeta{
Name: "testAgentwithtoolongofanamereallylongname",
Namespace: "test",
Generation: 2,
},
Status: agentv1alpha1.AgentStatus{
ObservedGeneration: 2,
},
},
wantErr: true,
},
}
for _, tt := range tests {
naemono marked this conversation as resolved.
Show resolved Hide resolved
t.Run(tt.name, func(t *testing.T) {
r := newReconcileAgent(tt.objs...)
got, err := r.Reconcile(context.Background(), tt.request)
if (err != nil) != tt.wantErr {
t.Errorf("ReconcileAgent.Reconcile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ReconcileAgent.Reconcile() = %v, want %v", got, tt.want)
}

var agent agentv1alpha1.Agent
if err := r.Client.Get(context.Background(), tt.request.NamespacedName, &agent); err != nil {
t.Error(err)
return
}
// AllowUnexported required because of *AssocConf on the agent.
comparison.AssertEqual(t, &agent, &tt.expected, cmp.AllowUnexported(agentv1alpha1.Agent{}))
})
}
}
17 changes: 15 additions & 2 deletions pkg/controller/agent/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ import (
)

const (
// FleetServerPort is the standard Elastic Fleet Server port.
FleetServerPort int32 = 8220
)

// Params are a set of parameters used during internal reconciliation of Elastic Agents.
type Params struct {
Context context.Context

Expand All @@ -46,18 +48,22 @@ type Params struct {
OperatorParams operator.Parameters
}

// K8sClient returns the Kubernetes client.
func (p Params) K8sClient() k8s.Client {
return p.Client
}

// Recorder returns the Kubernetes event recorder.
func (p Params) Recorder() record.EventRecorder {
return p.EventRecorder
}

// DynamicWatches returns the set of stateful dynamic watches used during reconciliation.
func (p Params) DynamicWatches() watches.DynamicWatches {
return p.Watches
}

// GetPodTemplate returns the configured pod template for the associated Elastic Agent.
func (p *Params) GetPodTemplate() corev1.PodTemplateSpec {
if p.Agent.Spec.DaemonSet != nil {
return p.Agent.Spec.DaemonSet.PodTemplate
Expand All @@ -66,11 +72,18 @@ func (p *Params) GetPodTemplate() corev1.PodTemplateSpec {
return p.Agent.Spec.Deployment.PodTemplate
}

// Logger returns the configured logger for use during reconciliation.
func (p *Params) Logger() logr.Logger {
return log.FromContext(p.Context)
}

func internalReconcile(params Params) *reconciler.Results {
func newStatus(agent agentv1alpha1.Agent) agentv1alpha1.AgentStatus {
status := agent.Status
status.ObservedGeneration = agent.Generation
return status
}

func internalReconcile(params Params, status *agentv1alpha1.AgentStatus) *reconciler.Results {
defer tracing.Span(&params.Context)()
results := reconciler.NewResult(params.Context)

Expand Down Expand Up @@ -122,7 +135,7 @@ func internalReconcile(params Params) *reconciler.Results {
if err != nil {
return results.WithError(err)
}
return results.WithResults(reconcilePodVehicle(params, podTemplate))
return results.WithResults(reconcilePodVehicle(params, podTemplate, status))
}

func reconcileService(params Params) (*corev1.Service, error) {
Expand Down
3 changes: 2 additions & 1 deletion pkg/controller/agent/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

const (
// Type represents the Agent type.
// TypeLabelValue represents the Agent type.
TypeLabelValue = "agent"

// NameLabelName used to represent an Agent in k8s resources
Expand All @@ -20,6 +20,7 @@ const (
NamespaceLabelName = "agent.k8s.elastic.co/namespace"
)

// NewLabels returns the set of common labels for an Elastic Agent.
func NewLabels(agent agentv1alpha1.Agent) map[string]string {
return map[string]string{
common.TypeLabelName: TypeLabelValue,
Expand Down
Loading