Skip to content

Commit

Permalink
Add manager package and general housekeeping
Browse files Browse the repository at this point in the history
  • Loading branch information
jveski committed Nov 13, 2023
1 parent c4dbbd4 commit d68b54f
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 57 deletions.
11 changes: 7 additions & 4 deletions api/v1/composition.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,13 @@ type Synthesis struct {
// metadata.generation of the Composition at the time of synthesis.
ObservedGeneration int64 `json:"observedGeneration,omitempty"`

// metadata.generation of the Synthesizer at the time of synthesis.
ObservedSynthesizerGeneration *int64 `json:"observedSynthesizerGeneration,omitempty"`

// Number of resulting resource slices. Since they are immutable, this provides adequate timing signal to avoid stale informer caches.
ResourceSliceCount int64 `json:"resourceSliceCount,omitempty"`
ResourceSliceCount *int64 `json:"resourceSliceCount,omitempty"`

Ready bool `json:"ready,omitempty"`
Synced bool `json:"synced,omitempty"`
PodCreation metav1.Time `json:"podCreation,omitempty"`
Ready bool `json:"ready,omitempty"`
Synced bool `json:"synced,omitempty"`
PodCreation *metav1.Time `json:"podCreation,omitempty"`
}
10 changes: 10 additions & 0 deletions api/v1/config/crd/eno.azure.io_compositions.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ spec:
of synthesis.
format: int64
type: integer
observedSynthesizerGeneration:
description: metadata.generation of the Synthesizer at the time
of synthesis.
format: int64
type: integer
podCreation:
format: date-time
type: string
Expand All @@ -98,6 +103,11 @@ spec:
of synthesis.
format: int64
type: integer
observedSynthesizerGeneration:
description: metadata.generation of the Synthesizer at the time
of synthesis.
format: int64
type: integer
podCreation:
format: date-time
type: string
Expand Down
6 changes: 6 additions & 0 deletions api/v1/config/crd/eno.azure.io_synthesizers.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ spec:
complete.
format: int64
type: integer
lastRolloutTime:
description: LastRolloutTime is the timestamp of the last pod creation
caused by a change to this resource. Should not be updated due to
Composotion changes. Used to calculate rollout cooldown period.
format: date-time
type: string
type: object
type: object
served: true
Expand Down
9 changes: 8 additions & 1 deletion api/v1/synthesizer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package v1

import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +kubebuilder:object:root=true
type SynthesizerList struct {
Expand Down Expand Up @@ -29,6 +31,11 @@ type SynthesizerStatus struct {
// The metadata.generation of this resource at the oldest version currently used by any Generations.
// This will equal the current generation when slow rollout of an update to the Generations is complete.
CurrentGeneration int64 `json:"currentGeneration,omitempty"`

// LastRolloutTime is the timestamp of the last pod creation caused by a change to this resource.
// Should not be updated due to Composotion changes.
// Used to calculate rollout cooldown period.
LastRolloutTime *metav1.Time `json:"lastRolloutTime,omitempty"`
}

type SynthesizerRef struct {
Expand Down
21 changes: 19 additions & 2 deletions api/v1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions internal/manager/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package manager

import (
"context"
"fmt"

"github.com/go-logr/logr"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"

apiv1 "github.com/Azure/eno/api/v1"
)

const (
IdxSlicesByCompositionGeneration = ".metadata.ownerReferences.compositionGen" // see: NewSlicesByCompositionGenerationKey
)

func New(cfg *rest.Config, logger logr.Logger) (ctrl.Manager, error) {
mgr, err := ctrl.NewManager(cfg, manager.Options{
Logger: logger,
})
if err != nil {
return nil, err
}

err = apiv1.SchemeBuilder.AddToScheme(mgr.GetScheme())
if err != nil {
return nil, err
}

err = mgr.GetFieldIndexer().IndexField(context.Background(), &apiv1.ResourceSlice{}, IdxSlicesByCompositionGeneration, func(o client.Object) []string {
slice := o.(*apiv1.ResourceSlice)
owner := metav1.GetControllerOf(slice)
if owner == nil || owner.Kind != "Composition" {
return nil
}
return []string{NewSlicesByCompositionGenerationKey(owner.Name, slice.Spec.CompositionGeneration)}
})
if err != nil {
return nil, err
}

return mgr, nil
}

func NewLogConstructor(mgr ctrl.Manager, controllerName string) func(*reconcile.Request) logr.Logger {
return func(req *reconcile.Request) logr.Logger {
l := mgr.GetLogger().WithValues("controller", controllerName)
if req != nil {
l.WithValues("requestName", req.Name, "requestNamespace", req.Namespace)
}
return l
}
}

// NewSlicesByCompositionGenerationKey documents the key structure used by IdxSlicesByCompositionGeneration.
func NewSlicesByCompositionGenerationKey(compName string, compGeneration int64) string {
// keys will not collide because k8s doesn't allow slashes in names
return fmt.Sprintf("%s/%d", compName, compGeneration)
}
30 changes: 10 additions & 20 deletions internal/reconstitution/reconstituter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import (
"sync/atomic"

k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/workqueue"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"

apiv1 "github.com/Azure/eno/api/v1"
"github.com/Azure/eno/internal/manager"
"github.com/go-logr/logr"
)

Expand All @@ -28,30 +28,16 @@ type reconstituter struct {
}

func newReconstituter(mgr ctrl.Manager) (*reconstituter, error) {
// Index resource slices by the specific synthesis they originate from
err := mgr.GetFieldIndexer().IndexField(context.Background(), &apiv1.ResourceSlice{}, indexName, func(o client.Object) []string {
slice := o.(*apiv1.ResourceSlice)
owner := metav1.GetControllerOf(slice)
if owner == nil || owner.Kind != "Composition" {
return nil
}
// keys will not collide because k8s doesn't allow slashes in names
return []string{fmt.Sprintf("%s/%d", owner.Name, slice.Spec.CompositionGeneration)}
})
if err != nil {
return nil, err
}

r := &reconstituter{
cache: newCache(mgr.GetClient()),
client: mgr.GetClient(),
}
_, err = ctrl.NewControllerManagedBy(mgr).
return r, ctrl.NewControllerManagedBy(mgr).
Named("reconstituter").
For(&apiv1.Composition{}).
Owns(&apiv1.ResourceSlice{}).
Build(r)
return r, err
WithLogConstructor(manager.NewLogConstructor(mgr, "reconstituter")).
Complete(r)
}

func (r *reconstituter) AddQueue(queue workqueue.Interface) {
Expand Down Expand Up @@ -96,6 +82,10 @@ func (r *reconstituter) populateCache(ctx context.Context, comp *apiv1.Compositi
if synthesis == nil {
return nil
}
if synthesis.ResourceSliceCount == nil {
logger.V(1).Info("resource synthesis is not complete - waiting to fill cache")
return nil
}
compNSN := types.NamespacedName{Namespace: comp.Namespace, Name: comp.Name}

logger = logger.WithValues("synthesisGen", synthesis.ObservedGeneration)
Expand All @@ -107,14 +97,14 @@ func (r *reconstituter) populateCache(ctx context.Context, comp *apiv1.Compositi

slices := &apiv1.ResourceSliceList{}
err := r.client.List(ctx, slices, client.InNamespace(comp.Namespace), client.MatchingFields{
indexName: fmt.Sprintf("%s/%d", comp.Name, synthesis.ObservedGeneration),
manager.IdxSlicesByCompositionGeneration: manager.NewSlicesByCompositionGenerationKey(comp.Name, synthesis.ObservedGeneration),
})
if err != nil {
return fmt.Errorf("listing resource slices: %w", err)
}

logger.V(1).Info(fmt.Sprintf("found %d slices for this synthesis", len(slices.Items)))
if int64(len(slices.Items)) != synthesis.ResourceSliceCount {
if int64(len(slices.Items)) != *synthesis.ResourceSliceCount {
logger.V(1).Info("stale informer - waiting for sync")
return nil
}
Expand Down
3 changes: 2 additions & 1 deletion internal/reconstitution/reconstituter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ func TestReconstituterIntegration(t *testing.T) {
comp.Namespace = "default"
require.NoError(t, client.Create(ctx, comp))

one := int64(1)
comp.Status.CurrentState = &apiv1.Synthesis{
ObservedGeneration: comp.Generation,
ResourceSliceCount: 1,
ResourceSliceCount: &one,
}
require.NoError(t, client.Status().Update(ctx, comp))

Expand Down
10 changes: 4 additions & 6 deletions internal/reconstitution/writebuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ type asyncStatusUpdate struct {
// updates over a short period of time and applying them in a single update request.
type writeBuffer struct {
client client.Client
logger logr.Logger

// queue items are per-slice.
// the state map collects multiple updates per slice to be dispatched by next queue item.
Expand All @@ -34,10 +33,9 @@ type writeBuffer struct {
queue workqueue.RateLimitingInterface
}

func newWriteBuffer(cli client.Client, logger logr.Logger, batchInterval time.Duration, burst int) *writeBuffer {
func newWriteBuffer(cli client.Client, batchInterval time.Duration, burst int) *writeBuffer {
return &writeBuffer{
client: cli,
logger: logger.WithValues("controller", "writeBuffer"),
state: make(map[types.NamespacedName][]*asyncStatusUpdate),
queue: workqueue.NewRateLimitingQueueWithConfig(
&workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Every(batchInterval), burst)},
Expand Down Expand Up @@ -80,14 +78,14 @@ func (w *writeBuffer) processQueueItem(ctx context.Context) bool {
defer w.queue.Done(item)
sliceNSN := item.(types.NamespacedName)

logger := logr.FromContextOrDiscard(ctx).WithValues("slice", sliceNSN, "controller", "writeBuffer")
ctx = logr.NewContext(ctx, logger)

w.mut.Lock()
updates := w.state[sliceNSN]
delete(w.state, sliceNSN)
w.mut.Unlock()

logger := w.logger.WithValues("slice", sliceNSN)
ctx = logr.NewContext(ctx, logger)

if len(updates) == 0 {
logger.V(0).Info("dropping queue item because no updates were found for this slice (this is suspicious)")
}
Expand Down
Loading

0 comments on commit d68b54f

Please sign in to comment.