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

Add metrics reporting for mutation #1435

Merged
merged 78 commits into from
Jul 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
78 commits
Select commit Hold shift + click to select a range
509fa68
Include v1 ConstraintTemplate from frameworks (#1416)
julianKatz Jul 8, 2021
c8caaa0
allow helm chart to override failurePolicy (#1417)
helayoty Jul 10, 2021
4c452ea
Add prefix-based matching for namespaces and excludedNamespaces (#1404)
julianKatz Jul 12, 2021
9c701e6
Brought a bunch of boilerplate into pkg/mutation/stats_reporter_test.go
julianKatz Jul 12, 2021
c85ea89
Added some View information
julianKatz Jul 12, 2021
9ef9793
Boilerplate tests are passing for TestReportMutatorIngestionRequest
julianKatz Jul 12, 2021
c8606b2
Added verifyTags function
julianKatz Jul 12, 2021
d9ef014
Added reportMutatorsStatus with unit test
julianKatz Jul 13, 2021
4800f9a
Added reporting function for iteration convergance + tests
julianKatz Jul 13, 2021
a0e7c16
Remove non-specific webhook request metrics (#1428)
julianKatz Jul 13, 2021
5552d82
Preserve conflicting schemas and report conflicts (#1364)
Jul 13, 2021
42d5320
Some test refactoring, made distributon fibonacci for mutator iterations
julianKatz Jul 13, 2021
8cf587f
Update GK minimum version and reasoning. (#1432)
Jul 13, 2021
d47e015
[gk-test] parse Templates + Constraints in Suites (#1419)
Jul 13, 2021
45c3ba5
auto format linters (#1433)
Jul 13, 2021
da2624e
Add reporter to mutation system
julianKatz Jul 13, 2021
9af8bd4
Add reportMutatorIngestionRequest to System.Upsert
julianKatz Jul 13, 2021
2d9d504
Add a map that tracks the status of mutator ingestion
julianKatz Jul 14, 2021
4bdfb14
Add mutator ingestion status reporting calls to System public functions
julianKatz Jul 14, 2021
b5d7a00
Force type assertions (#1436)
Jul 13, 2021
c8736d8
make resourcequota and priorityClassName's optional (#1425)
developer-guy Jul 14, 2021
a8328c3
Use containerized kustomize (#1395)
Jul 14, 2021
aa593e0
Benchmark AssignMutator.Mutate code (#1437)
Jul 14, 2021
63cf601
Fix removal from ingestionStatusMap
julianKatz Jul 14, 2021
59b9c36
Revert "Add reporter to mutation system"
julianKatz Jul 15, 2021
da7bd65
Move mutation stats_reporter into a sub package
julianKatz Jul 19, 2021
089c3d6
Move reporting into controllers
julianKatz Jul 19, 2021
162d058
Make dependabot-recommended changes (#1440)
Jul 16, 2021
eee16c8
[mutation] Cache tester in AssignMetadata like we do in Assign mutato…
Jul 17, 2021
2de9e98
benchmark AssignMetadata.Mutate (#1441)
Jul 17, 2021
1810547
Fix lint errors
julianKatz Jul 19, 2021
6926079
Remove erroneous print statement (#1452)
Jul 19, 2021
03b15d0
ReportIterationConvergence in mutaiton system
julianKatz Jul 19, 2021
453ad48
Do a full change of InjectMutationCache --> InjectMutationSystem
julianKatz Jul 19, 2021
11e1678
Remove some unnecessary comments
julianKatz Jul 19, 2021
ec3fc35
Aesthetic improvements
julianKatz Jul 19, 2021
a37bdcf
Changed all the mutationCache to mutationSystem
julianKatz Jul 19, 2021
a394198
Make reporter a passed-through type
julianKatz Jul 20, 2021
6c913ac
More making statsreporter an argument
julianKatz Jul 20, 2021
4435835
Made mutation system accept a StatsReporter instead of making its own
julianKatz Jul 20, 2021
9b5e6ec
Change NewStatsReporter to NewMetricsReporter
julianKatz Jul 20, 2021
0260114
Refactor run code into Runner (#1445)
Jul 20, 2021
57753a4
deepcopy cached value instead of unmarshalling json (#1439)
Jul 20, 2021
df2613f
Make mutation.System take an interface type for its reporting functions
julianKatz Jul 20, 2021
88b3c28
Copied mutation controller related metrics into new package:
julianKatz Jul 21, 2021
fbf71c9
Moved the mutator controllers into a sub folder of pkg/controller
julianKatz Jul 21, 2021
33613bb
Move the mutator controller stats reporting code into pkg/controller/…
julianKatz Jul 21, 2021
3d562b3
Move the cache and update references
julianKatz Jul 21, 2021
b17d370
Fix race conditions in watch manager and constraint controllers (#1427)
maxsmythe Jul 21, 2021
88e21d4
Bump codecov/codecov-action from 1.5.2 to 2.0.1 (#1456)
dependabot[bot] Jul 21, 2021
cfa4948
Make the SystemReporter interface injectable, instead of as arg in Ne…
julianKatz Jul 21, 2021
bf2ca22
Detach the mutator controllers from the global statsreporter
julianKatz Jul 21, 2021
10c0a67
Make NewSystem not take any arguments
julianKatz Jul 21, 2021
6a2c401
Get rid of unnecessary interface in mutation system reporting and add…
julianKatz Jul 21, 2021
c23e62e
Bump actions/setup-node from 2.2.0 to 2.3.0 (#1459)
dependabot[bot] Jul 22, 2021
1724dc7
Fix a lint error
julianKatz Jul 22, 2021
8356ac2
Get rid of unnecessary interface in mutation system reporting and add…
julianKatz Jul 21, 2021
a053971
Remove a comment
julianKatz Jul 22, 2021
eb5c20c
Add metrics reporting for mutation
julianKatz Jul 22, 2021
071c335
Move large defer function into a method
julianKatz Jul 23, 2021
ca1f98e
Put view registration inside of init() functions
julianKatz Jul 23, 2021
16113be
Removed tag.New() calls, simplifying context creation
julianKatz Jul 26, 2021
cd6e768
Reduce System.Mutate runtime by 87% (#1454)
Jul 26, 2021
2415ea8
Update mutation/stats_reporter_test to use got X, want Y syntax
julianKatz Jul 26, 2021
d97171d
Create a raw context in mutation/stats_reporter constructor. Remove …
julianKatz Jul 26, 2021
5affb41
Change context.Background to context.TODO in mutation stats reporters
julianKatz Jul 26, 2021
74ce060
Better use of accessory functions in unit tests
julianKatz Jul 26, 2021
2ad4ebe
A few things:
julianKatz Jul 26, 2021
9ef0933
Updated incorrect description of systemIterationsM
julianKatz Jul 26, 2021
139aa20
Change fibonacci sequence to logarithmic sequence
julianKatz Jul 27, 2021
f9dbebe
incasing --> encasing
julianKatz Jul 27, 2021
001e8a0
Removed the last two JULIAN comments
julianKatz Jul 27, 2021
5b1c9b4
Bump codecov/codecov-action from 2.0.1 to 2.0.2 (#1462)
dependabot[bot] Jul 27, 2021
7acf4a7
Merge branch 'master' of github.com:open-policy-agent/gatekeeper into…
julianKatz Jul 27, 2021
fa4d39f
Removed unnecessary comments
julianKatz Jul 27, 2021
a744801
Merge branch 'master' of github.com:open-policy-agent/gatekeeper into…
julianKatz Jul 29, 2021
75398e9
Merge branch 'master' of github.com:open-policy-agent/gatekeeper into…
julianKatz Jul 29, 2021
4115741
Merge branch 'master' of github.com:open-policy-agent/gatekeeper into…
julianKatz Jul 29, 2021
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
8 changes: 5 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,12 +244,13 @@ func setupControllers(mgr ctrl.Manager, sw *watch.ControllerSwitch, tracker *rea
setupLog.Error(err, "unable to set up OPA backend")
os.Exit(1)
}

client, err := backend.NewClient(opa.Targets(&target.K8sValidationTarget{}))
if err != nil {
setupLog.Error(err, "unable to set up OPA client")
}

mutationCache := mutation.NewSystem()
mutationSystem := mutation.NewSystem(mutation.SystemOpts{Reporter: mutation.NewStatsReporter()})

c := mgr.GetCache()
dc, ok := c.(watch.RemovableCache)
Expand All @@ -258,6 +259,7 @@ func setupControllers(mgr ctrl.Manager, sw *watch.ControllerSwitch, tracker *rea
setupLog.Error(err, "fetching dynamic cache")
os.Exit(1)
}

wm, err := watch.New(dc)
if err != nil {
setupLog.Error(err, "unable to create watch manager")
Expand All @@ -279,7 +281,7 @@ func setupControllers(mgr ctrl.Manager, sw *watch.ControllerSwitch, tracker *rea
ControllerSwitch: sw,
Tracker: tracker,
ProcessExcluder: processExcluder,
MutationCache: mutationCache,
MutationSystem: mutationSystem,
}
if err := controller.AddToManager(mgr, opts); err != nil {
setupLog.Error(err, "unable to register controllers with the manager")
Expand All @@ -288,7 +290,7 @@ func setupControllers(mgr ctrl.Manager, sw *watch.ControllerSwitch, tracker *rea

if operations.IsAssigned(operations.Webhook) {
setupLog.Info("setting up webhooks")
if err := webhook.AddToManager(mgr, client, processExcluder, mutationCache); err != nil {
if err := webhook.AddToManager(mgr, client, processExcluder, mutationSystem); err != nil {
setupLog.Error(err, "unable to register webhooks with the manager")
os.Exit(1)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/controller/add_assign.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.
package controller

import (
"github.com/open-policy-agent/gatekeeper/pkg/controller/assign"
"github.com/open-policy-agent/gatekeeper/pkg/controller/mutators/assign"
)

func init() {
Expand Down
2 changes: 1 addition & 1 deletion pkg/controller/add_assignmetadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.
package controller

import (
"github.com/open-policy-agent/gatekeeper/pkg/controller/assignmetadata"
"github.com/open-policy-agent/gatekeeper/pkg/controller/mutators/assignmetadata"
)

func init() {
Expand Down
2 changes: 1 addition & 1 deletion pkg/controller/config/config_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (a *Adder) InjectProcessExcluder(m *process.Excluder) {
a.ProcessExcluder = m
}

func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {}
func (a *Adder) InjectMutationSystem(mutationSystem *mutation.System) {}

// newReconciler returns a new reconcile.Reconciler
// events is the channel from which sync controller will receive the events
Expand Down
16 changes: 6 additions & 10 deletions pkg/controller/constraint/constraint_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (a *Adder) InjectTracker(t *readiness.Tracker) {
a.Tracker = t
}

func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {}
func (a *Adder) InjectMutationSystem(mutationSystem *mutation.System) {}

// Add creates a new Constraint Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
Expand Down Expand Up @@ -473,15 +473,11 @@ func (c *ConstraintsCache) reportTotalConstraints(reporter StatsReporter) {

for _, enforcementAction := range util.KnownEnforcementActions {
for _, status := range metrics.AllStatuses {
if err := reporter.reportConstraints(
tags{
enforcementAction: enforcementAction,
status: status,
},
int64(totals[tags{
enforcementAction: enforcementAction,
status: status,
}])); err != nil {
t := tags{
enforcementAction: enforcementAction,
status: status,
}
if err := reporter.reportConstraints(t, int64(totals[t])); err != nil {
log.Error(err, "failed to report total constraints")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func (a *Adder) InjectGetPod(getPod func() (*corev1.Pod, error)) {
a.GetPod = getPod
}

func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {}
func (a *Adder) InjectMutationSystem(mutationSystem *mutation.System) {}

// newReconciler returns a new reconcile.Reconciler
// cstrEvents is the channel from which constraint controller will receive the events
Expand Down
6 changes: 3 additions & 3 deletions pkg/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type Injector interface {
InjectWatchManager(*watch.Manager)
InjectControllerSwitch(*watch.ControllerSwitch)
InjectTracker(tracker *readiness.Tracker)
InjectMutationCache(mutationCache *mutation.System)
InjectMutationSystem(mutationSystem *mutation.System)
Add(mgr manager.Manager) error
}

Expand All @@ -71,7 +71,7 @@ type Dependencies struct {
Tracker *readiness.Tracker
GetPod func() (*corev1.Pod, error)
ProcessExcluder *process.Excluder
MutationCache *mutation.System
MutationSystem *mutation.System
}

type defaultPodGetter struct {
Expand Down Expand Up @@ -149,7 +149,7 @@ func AddToManager(m manager.Manager, deps Dependencies) error {
a.InjectWatchManager(deps.WatchManger)
a.InjectControllerSwitch(deps.ControllerSwitch)
a.InjectTracker(deps.Tracker)
a.InjectMutationCache(deps.MutationCache)
a.InjectMutationSystem(deps.MutationSystem)
if a2, ok := a.(GetPodInjector); ok {
a2.InjectGetPod(deps.GetPod)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ package assign
import (
"context"
"fmt"
"time"

opa "github.com/open-policy-agent/frameworks/constraint/pkg/client"
mutationsv1alpha1 "github.com/open-policy-agent/gatekeeper/apis/mutations/v1alpha1"
statusv1beta1 "github.com/open-policy-agent/gatekeeper/apis/status/v1beta1"
ctrlmutators "github.com/open-policy-agent/gatekeeper/pkg/controller/mutators"
"github.com/open-policy-agent/gatekeeper/pkg/controller/mutatorstatus"
"github.com/open-policy-agent/gatekeeper/pkg/logging"
"github.com/open-policy-agent/gatekeeper/pkg/mutation"
Expand Down Expand Up @@ -55,15 +57,15 @@ var gvkAssign = schema.GroupVersionKind{
}

type Adder struct {
MutationCache *mutation.System
Tracker *readiness.Tracker
GetPod func() (*corev1.Pod, error)
MutationSystem *mutation.System
Tracker *readiness.Tracker
GetPod func() (*corev1.Pod, error)
}

// Add creates a new Assign Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func (a *Adder) Add(mgr manager.Manager) error {
r := newReconciler(mgr, a.MutationCache, a.Tracker, a.GetPod)
r := newReconciler(mgr, a.MutationSystem, a.Tracker, a.GetPod)
return add(mgr, r)
}

Expand All @@ -81,18 +83,20 @@ func (a *Adder) InjectGetPod(getPod func() (*corev1.Pod, error)) {
a.GetPod = getPod
}

func (a *Adder) InjectMutationCache(mutationCache *mutation.System) {
a.MutationCache = mutationCache
func (a *Adder) InjectMutationSystem(mutationSystem *mutation.System) {
a.MutationSystem = mutationSystem
}

// newReconciler returns a new reconcile.Reconciler.
func newReconciler(mgr manager.Manager, mutationCache *mutation.System, tracker *readiness.Tracker, getPod func() (*corev1.Pod, error)) *Reconciler {
func newReconciler(mgr manager.Manager, mutationSystem *mutation.System, tracker *readiness.Tracker, getPod func() (*corev1.Pod, error)) *Reconciler {
r := &Reconciler{
system: mutationCache,
Client: mgr.GetClient(),
tracker: tracker,
getPod: getPod,
scheme: mgr.GetScheme(),
system: mutationSystem,
Client: mgr.GetClient(),
tracker: tracker,
getPod: getPod,
scheme: mgr.GetScheme(),
reporter: ctrlmutators.NewStatsReporter(),
cache: ctrlmutators.NewMutationCache(),
}
if getPod == nil {
r.getPod = r.defaultGetPod
Expand Down Expand Up @@ -133,25 +137,31 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Reconciler reconciles a Assign object.
type Reconciler struct {
client.Client
system *mutation.System
tracker *readiness.Tracker
getPod func() (*corev1.Pod, error)
scheme *runtime.Scheme
system *mutation.System
tracker *readiness.Tracker
getPod func() (*corev1.Pod, error)
scheme *runtime.Scheme
reporter ctrlmutators.StatsReporter
cache *ctrlmutators.Cache
}

// +kubebuilder:rbac:groups=mutations.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete

// Reconcile reads that state of the cluster for a Assign object and makes changes based on the state read
// and what is in the Assign.Spec.
// TODO (https://github.com/open-policy-agent/gatekeeper/issues/1449): DRY this and assignmetadata_controller.go .
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log.Info("Reconcile", "request", request)
startTime := time.Now()

deleted := false
assign := &mutationsv1alpha1.Assign{}
err := r.Get(ctx, request.NamespacedName, assign)
if err != nil {
if !errors.IsNotFound(err) {
return reconcile.Result{}, err
}

deleted = true
assign = &mutationsv1alpha1.Assign{
ObjectMeta: metav1.ObjectMeta{
Expand All @@ -171,6 +181,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (

if deleted {
tracker.CancelExpect(assign)
r.cache.Remove(mID)

if err := r.system.Remove(mID); err != nil {
log.Error(err, "Remove failed", "resource", request.NamespacedName)
Expand All @@ -193,6 +204,10 @@ func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (
return reconcile.Result{}, nil
}

ingestionStatus := ctrlmutators.MutatorStatusError
// encasing this call in a function prevents the arguments from being evaluated early
defer func() { r.reportMutator(mID, ingestionStatus, startTime) }()

status, err := r.getOrCreatePodStatus(mID)
if err != nil {
log.Info("could not get/create pod status object", "error", err)
Expand Down Expand Up @@ -230,6 +245,8 @@ func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (
log.Error(err, "could not update mutator status")
return reconcile.Result{}, err
}

ingestionStatus = ctrlmutators.MutatorStatusActive
return reconcile.Result{}, nil
}

Expand Down Expand Up @@ -266,3 +283,21 @@ func (r *Reconciler) defaultGetPod() (*corev1.Pod, error) {
// guarantee we don't inadvertently create a watch
panic("GetPod must be injected")
}

func (r *Reconciler) reportMutator(mID types.ID, ingestionStatus ctrlmutators.MutatorIngestionStatus, startTime time.Time) {
r.cache.Upsert(mID, ingestionStatus)

if r.reporter == nil {
return
}

if err := r.reporter.ReportMutatorIngestionRequest(ingestionStatus, time.Since(startTime)); err != nil {
log.Error(err, "failed to report mutator ingestion request")
}

for status, count := range r.cache.Tally() {
if err := r.reporter.ReportMutatorsStatus(status, count); err != nil {
log.Error(err, "failed to report mutator status request")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ var cfg *rest.Config
func TestMain(m *testing.M) {
t := &envtest.Environment{
CRDDirectoryPaths: []string{
filepath.Join("..", "..", "..", "vendor", "github.com", "open-policy-agent", "frameworks", "constraint", "deploy", "crds.yaml"),
filepath.Join("..", "..", "..", "config", "crd", "bases"),
filepath.Join("..", "..", "..", "..", "vendor", "github.com", "open-policy-agent", "frameworks", "constraint", "deploy", "crds.yaml"),
filepath.Join("..", "..", "..", "..", "config", "crd", "bases"),
},
ErrorIfCRDPathMissing: true,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ func TestReconcile(t *testing.T) {
// force mutation to be enabled
*mutation.MutationEnabled = true

mSys := mutation.NewSystem()
mSys := mutation.NewSystem(mutation.SystemOpts{})

tracker, err := readiness.SetupTracker(mgr, true)
g.Expect(err).NotTo(gomega.HaveOccurred())
os.Setenv("POD_NAME", "no-pod")
Expand Down
Loading