Commit Graph

62 Commits

Author SHA1 Message Date
Dave Protasowski 8535fcc248
gofumpt the repo (#3067)
* gofumpt the repo

* don't prefix numbers with 0 - otherwise they're octal
2024-06-25 07:27:07 +00:00
Stavros Kontopoulos 8d3f951063
Allow overriding webhook secret data keys (#2662)
* override secret data keys when creating new webhooks

* fixes

* cleanup

* use webhook options

* remove unused env var keys

* fix docs

* update opt names and refactor integration test

* fixes
2023-08-02 19:19:48 +00:00
Dave Protasowski 9bda38b216
Fix some webhook testing tech debt (#2751)
* TestRegistrationStopChanFire now uses ephemeral ports

* For TLS servers dial TLS

* have server error logs appear in zap

* log the correct error

* pass ephemeral listeners to the webhook for testing
2023-05-25 14:35:25 +00:00
Izabela Gomes 53f04b373c
Make minimum TLS version configurable for webhooks (#2721)
* make minimum tls version configurable

* change default min TLS version to 1.3

* change opencensus tls min version to 1.3

* Update env var name

Co-authored-by: Dave Protasowski <dprotaso@gmail.com>

* use webhook options to configure min tls version

* add unit tests for webhook tlsMinVersion option

* Update webhook/env.go

Co-authored-by: Dave Protasowski <dprotaso@gmail.com>

* address feeback

---------

Co-authored-by: Dave Protasowski <dprotaso@gmail.com>
2023-04-14 15:45:51 +00:00
Todd 9b5c41135d
allow overriding the default grace period of 45 seconds (#2423)
This allows users to configure a faster restart of their
webhook if desired while retaining the current behavior.
2022-02-28 11:40:09 -08:00
Markus Thömmes c326b70b83
Add RunAndSyncInformers helper that makes sure informers are synced in tests (#2055)
* Add RunAndSyncInformers helper that makes sure informers are synced in tests

* Review stuff

* Drop Println
2021-03-10 23:53:26 -08:00
Victor Agababov a371418524
v2 (#1754) 2020-09-29 13:18:29 -07:00
Matt Moore e193c4be24
Implement a new shared "Drainer" handler. (#1517)
* Implement a new shared "Drainer" handler.

This implements a new `http.Handler` called `Drainer`, which is intended to wrap some inner `http.Handler` business logic with a new outer handler that can respond to Kubelet probes (successfully until told to "Drain()").

This takes over the webhook's relatively new probe handling and lame duck logic with one key difference.  Previously the webhook waited for a fixed period after SIGTERM before exitting, but the new logic waits for this same grace period AFTER THE LAST REQUEST.  So if the handler keeps getting (non-probe) requests, the timer will continually reset, and once it stops receiving requests for the configured grace period, "Drain()" will return and the webhook will exit.

The goal of this work is to try to better cope with what we believe to be high tail latencies of the API server seeing that a webhook replica is shutting down.

Related: https://github.com/knative/pkg/issues/1509

* Switch to RWLock
2020-07-17 21:25:34 -07:00
Victor Agababov 389d28f9b6
Use the generic networking constant for shutdown (#1365)
- use standard const, which is better
- stop modifying the default in the test, which is ugh a bit :)
2020-05-29 09:47:02 -07:00
Dave Protasowski b0e3201ad2
Kubelet probes would result in the webhook writing the HTTP status twice (#1355)
* Kubelet probes would result in the webhook writing the HTTP status twice

Doesn't seem like it affected anything - just writes out some extra
log messages

* nits

* nits

* nits

* nits
2020-05-26 10:34:50 -07:00
Matt Moore b52862b1b3
Implement the K8s lifecycle in webhook. (#1318)
* Implement the K8s lifecycle in webhook.

The webhook never properly implemented the Kubernetes SIGTERM/SIGKILL
lifecycle, and doesn't even really support readiness probes today.  This
change enables folks to use a block like this on their webhook container:

```yaml
        readinessProbe: &probe
          periodSeconds: 1
          httpGet:
            scheme: HTTPS
            port: 8443
            httpHeaders:
            - name: k-kubelet-probe
              value: "webhook"
        livenessProbe: *probe
```

With this, the webhook won't report as `Ready` until a probe has succeeded,
and when the SIGTERM is received, we will start failing probes for a grace
period (so our Endpoint drops) before shutting down the webhook's HTTP Server.

This was uncovered by running the webhook across 10 replicas in Serving with
the "Goose" (https://github.com/knative/pkg/pull/1316) enabled for the e2e
tests.  The failure mode I saw was conversion webhook requests failing across
random tests.

This also moves the Serving probe-detection function into PKG.

* Increase the log level when we start to fail probes

* Wait for go routines to terminate on all paths.
2020-05-09 16:44:45 -07:00
Markus Thömmes e983887dc4
Change default port in webhook test to 8443. (#1242)
A lot of systems have something running that responds on 443, i.e. a local test environment or a webserver.
2020-04-24 10:49:49 -07:00
Markus Thömmes c09083a601
Fix a few simple linter warnings: unused code, govet warnings etc. (#1191) 2020-04-06 08:21:20 -07:00
Dave Protasowski 88d4536182
Conversion Webhook Framework (#993)
* ConversionController implementation

This controller will reconcile target CRDs with the correct
conversion webhook configuration. Specifically, the HTTP path and
CA bundle will be updated.

Additionally, the conversion controller will perform the given
conversions through a hub and spoke model utilizing the
apis.Convertible interface.

* Webhook now can host ConversionControllers

* injection/sharedmain now supports webhook.ConversionControllers

These conversion controllers will be hosted by the webhook that
the sharedmain will start

* support defaulting & include godoc
2020-02-03 08:59:29 -08:00
Victor Agababov e4e8788a2c Fix the race in the webhook test. (#858)
The usual stuff: logger after test terminated.

/assign mattmoor
2019-11-08 10:24:56 -08:00
Markus Thömmes 56c2594e4f Assorted linting fixes. (#840)
* Remove unused code.

* Remove unneeded loops.

* Remove unneeded Printf calls.

* Use time.Since instead of time.Now().Sub.

* Remove unused values.

* Rename error variable according to conventions.

* Return error last.

* Simplify array allocations.

* Remove leaky ticker.

* Remove Yoda conditions.

* Remove deprecated function to talk to GKE.

* Remove dot import.

* Remove empty critical section and replace with a channel operation.

* Add linter directives to explicitly state wanted weirdness.

* Update deps.

* Fix broken line.
2019-11-01 12:49:12 -07:00
Matt Moore d4ce001394 This refactors our core webhook logic to be reconciler-based. (#833)
This is the culmination of a large number of changes to refactor our webhook logic, and adopt a reconciler-based approach to make it resilient to unexected system events (e.g. rogue GCs!).

For more details on how this is consumed, see the new `webhook/README.md`.

Fixes: https://github.com/knative/pkg/issues/782
Closes: https://github.com/knative/pkg/issues/529
Fixes: https://github.com/knative/pkg/issues/450
Related: https://github.com/knative/pkg/issues/141
2019-10-31 10:17:13 -07:00
Matt Moore 3732de5802 Split secret creation into our reconciler resources style. (#830) 2019-10-29 23:08:11 -07:00
Matt Moore 7772e2f583 Drive GetCertificate from the lister cache of a secret informer. (#825) 2019-10-29 07:11:12 -07:00
Matt Moore bfff3b7d72 Switch to using GetCertificate in tls.Config. (#823)
GetCertificate allows us to start in TLS mode and dynamically fetch new certificates as they change.  This will eventually allow us to decouple the cert creation process from the core webhook logic, and in a subsequent change service this from a secret lister cache.
2019-10-28 17:32:11 -07:00
Matt Moore da49e89aa8 Remove options to specify ClientAuth. (#822)
We don't use this anywhere in Knative downstream and it adds a bunch of complexity.
2019-10-28 16:50:11 -07:00
Matt Moore 763c642d3c Streamline `webhook.New`. (#821)
This now pulls most of its configuration from context, which brings it a step closer to aligning with our `sharedmain` package.
2019-10-28 16:12:11 -07:00
Matt Moore 3f2100ca91 Move WithContext into the resource admission controller. (#820) 2019-10-28 15:05:11 -07:00
Matt Moore aaf36e26c7 Accept a list of AdmissionControllers instead of a map (#819) 2019-10-28 14:09:11 -07:00
Matt Moore de53b8f09f Move hook-specific configuration options out of shared options. (#818)
This builds on https://github.com/knative/pkg/pull/817 and makes further
breaking changes. The options pertinent to each admission controller are
now passed to their respective constructors, which leads to a cleaner
options struct, and better prepares for greater webhook diversity.
2019-10-28 13:31:11 -07:00
Matt Moore 070396a075 Eliminate the Namespace config option in favor of system.Namespace. (#817) 2019-10-28 11:41:43 -07:00
Matt Moore cad41c40cc Stop using OwnerRefs for webhook config lifecycle (#802)
* Stop using OwnerRefs for webhook config lifecycle

This changes the model by which we manage the lifecycle of our
`{mutating,validating}webhookconfiguration`, which previously used an owner ref
from the cluster-scoped configuration to the namespace-scoped Deployment.  The
new model adds an explicit yaml file for the webhook, which omits the fields
filled in by the deployment as it starts.

A few notable elements of this change:
1. Clear out OwnerReferences explicitly (avoids the linked bug),
2. Periodically reruna `Register()` to ensure our webhook exists,
3. Simplified logic around registration (all we need now is update!).

Related: https://github.com/knative/serving/issues/5845

* Incorporate feedback from @dgerd and a few other nits I noticed.
2019-10-25 11:53:35 -07:00
Nima Kaviani d90ec6a015 add config validation as admission controller (#636) 2019-09-22 07:23:10 -07:00
Matt Moore e4ac97c252 Update our dependency on K8s libs to 1.15.3 (#686)
With a minimum K8s version of 1.14 (starting in 0.10), 1.15.3 puts us in the center of the +/-1 version window of support.
2019-09-18 13:36:48 -07:00
Nima Kaviani c39ee25c42 rename the variable for resource validation webhook (#653) 2019-09-11 06:40:29 -07:00
Nima Kaviani c270532140 introduce an interface for AdmissionControllers (#622) 2019-09-04 09:03:02 -07:00
Nima Kaviani 9118872a32 Refactor admission webhook (#595)
- decouple the webhool server from the controller
- move tests to respective files
2019-08-27 20:39:40 -07:00
Dan Gerdesmeier e2418a08c1 Change 'updater' to 'lastModifier' in webhook (#512)
* Change 'updater' to 'lastModifier' in webhook

Both eventing and serving curretly use lastModifier. Nothing seems to
implement the pkg 'HasSpec' interface yet so this should be a safe
change. This brings the annotation in-line with currentb behavior

Fixes #511

* Remove unnecessary defer

* Change paths in json patches
2019-07-09 17:58:59 -07:00
Annie Fu a68e009041 Add check for nil StatsReporter in webhook package (#518)
* Prevent nil StatsReporter for existing webhook package consumers

* Pass StatsReporter by pointer and have tests test constructor

* Make constructor return error instead of panicking

* Move StatsReporter to ControllerOptions to consolidate constructors
2019-07-09 17:23:58 -07:00
Annie Fu 84d3910c56 Add metrics to webhook package (#503)
* Add metrics to webhook package

Add metricstest package for shared helper functions for testing metrics

* Address PR

* Cleanup

* Fix import paths to fix build issues

* Fix import package path for test file

* Remove unnecessary formatting from error message

* Remove helper function only used once

* Add metric name to all error messages, make checkRowTags testing helper function

* Add common histogram bucket generator function to metrics package

* Fix CheckStatsNotReported check

* Reset metrics before each test so the tests are idempotent

* Make CheckStatsNotReported conditional clearer
2019-07-08 16:00:44 -07:00
mattmoor-sockpuppet 1864f499dc golang format tools (#497)
Produced via:
  `gofmt -s -w $(find -path './vendor' -prune -o -type f -name '*.go' -print))`
  `goimports -w $(find -name '*.go' | grep -v vendor)`
/assign @mattmoor
2019-06-27 07:37:08 -07:00
Matt Moore 222dd25986 Migrate pkg to use the knative.dev/pkg import path (#489)
* Manual changes.

* scripted changes.
2019-06-26 13:02:06 -07:00
Ali Ok 9f8e0692b7 #457 Duck type user annotation logic (#467)
* #457 Duck type user annotation logic

* #457 Duck type user annotation logic - tests

* #457 Revert updater annotation key from lastModifier to updater

* #457 Rename HasSpec#GetSpec() to HasSpec#GetUntypedSpec()

* #457 Fix some indentation

* #457 Get group for user info annotations from the request

* #457 Reduce confusuion in webhook testing by using same group
2019-06-24 18:20:05 -07:00
Scott Nichols 70ab9cc77d Adding Strict Validation based on struct.*Deprecated*Foo (#339)
* have simple tests. working on impl.

* strict setting, reflection based.

* ran codegen.

* adding license.

* update based on feedback and merge better.

* getting closer to something  simpler assuming shallow reflect.

* adding validation test.

* use the json tag.

* Golang things nil typed pointers are not nil.

* Use real value of reflect invalid.

* add a missing test.

* two methods, one for update, one for single check.

* checkdep is now in apis.

* fix pkg.

* Update apis/deprecated_test.go

Co-Authored-By: n3wscott <32305648+n3wscott@users.noreply.github.com>

* add code clarity.

* include inlined struct objects recursively.

* Update commnets and add a flatten error test for inlined.
2019-04-19 09:19:27 -07:00
mattmoor-sockpuppet a674efb8e1 Fix spelling errors (#378)
Produced via: `github.com/client9/misspell`
2019-04-10 06:40:58 -07:00
Matt Moore 2b574edcd7 Deprecate apis.Immutable and apis.Annotatable. (#368)
This deprecates the `apis.Immutable` and `apis.Annotatable` interfaces,
which were both awkward niche extensions of `apis.Validatable` and
`apis.SetDefaults` for specific contexts that the former set didn't
cover well.

With this change, the expectation is that types that want to check
for immutability will instead access the "baseline" object via the
context from within updates.  For example:

```
func (new *Type) Validate(ctx context.Context) *apis.FieldError {
  if apis.IsInUpdate(ctx) {
    old := apis.GetBaseline(ctx).(*Type)
    // Update specific validation based on new and old.
  }
}
```

For applying user annotations, the type writer can write:

```
func (new *Type) SetDefaults(ctx context.Context) {
  if apis.IsInCreate(ctx) {
    ui := apis.GetUserInfo(ctx)
    // Set creator annotation from ui
  }

  if apis.IsInUpdate(ctx) {
    ui := apis.GetUserInfo(ctx)
    old := apis.GetBaseline(ctx).(*Type)
    // Compare old.Spec vs. new.Spec and on changes
    // update the "updater" annotation from ui.
  }
}
```

One of the key motivations for this refactoring was to enable us
to do more powerful validation in `apis.Validate` beyond the niche
of immutability checking (and without introducing yet-another
one-off niche interface).  In the BYO Revision name PoC I abused
`apis.Immutable` to do more arbitrary before/after validation,
which with this can simply be a part of `apis.Validatable`.

See: https://github.com/knative/serving/pull/3562

The general stance on deprecating interfaces such as these will be
to deprecate them in a non-breaking way (via a comment for now). They
will be hollowed out when the functionality is removed from the webhook,
but left in because of diamond dependency problems.  In this change
we remove the `apis.Annotatable` functionality and deprecate the
`apis.Immutable` functionality.
2019-04-08 10:26:58 -07:00
Ville Aikas 8b3dc0d76d Use apps.Deployment instead of extensions.Deployment (#345)
* Use apps.Deployment instead of extensions.Deployment

* import as appsv1 instead of v1
2019-03-27 13:17:52 -07:00
Matt Moore 0f749ef7d5 This creates a way for clients of the webhook to decorate the request context. (#342)
Clients of webhook can now decorate the request context with additional metadata
via:
```
  ac := &AdmissionController{
    ... // As before
    WithContext: func(ctx context.Context) context.Context {
      // logic to attach stuff to ctx
    }
  }
```

This metadata can then be accessed off of the context in methods like
`SetDefaults` and `Validate` on types registered as webhook handlers.

Fixes: https://github.com/knative/pkg/issues/306
2019-03-26 21:33:51 -07:00
Matt Moore 04154dda9a Allow webhook implementations to optionally disallow unknown fields. (#338)
Related: https://github.com/knative/serving/issues/3309
2019-03-25 17:52:49 -07:00
Matt Moore 60fdcbcabd This threads a context.Context through the webhook interfaces we expose. (#332)
Related to: https://github.com/knative/pkg/issues/306
2019-03-21 10:48:48 -07:00
Dave Protasowski 0183bf9cdc Drop spec.generation support (#234)
* Drop webhook logic to increment spec.generation

With Kubernetes 1.11+ metadata.generation now increments properly
when the status subresource is enabled on CRDs

For more details see: https://github.com/knative/serving/issues/643

* Drop the generational duck type
2019-02-14 08:29:45 -08:00
Victor Agababov 1982208dd9 Initial commit for the webhook to set the annotations about mutator. (#275)
* Initial commit for the webhook to set the annotations about mutator.

The user that created or updated the resource will be set in the
annotations.

* update comments

* remove debug logging

* logging :/

* logging :/, returns

* logging :/ III

* error wrap

* simplify test

* rename the test

* add pkg/errors to the deps for better errors

* do not require CRD to implement Annotatable

* review issues

* fix interface as required by review
2019-02-12 21:03:43 -08:00
Victor Agababov dc1adcf1df Cleanup the webhook code. (#272)
* Cleanup the webhook code.

- add more tests
- fix formatting
- fix logging and errors
- use shorthands
- some optimizations in types
- make code more Go'ey from C'ey.

* raise test coverage
2019-02-12 09:12:44 -08:00
Adam Harwayne 25b3f456f0 Webhook creates a patch for all fields generated by Go (#243)
* Webhook creates a patch for all fields generated by round tripping the JSON through Golang types.

* Add unit tests for InnerDefaultResource.

* Linter errors.

* PR comments - test changes

* t.Helper()

* PR comments.
2019-02-06 14:32:40 -08:00
Victor Agababov a330baa9b0 Grep fix formatting issues (#233)
* Some fixes to the spoof.go and exporter.go

While reviewing some other CL, I saw some avenues for improving
spoof.go, to log the URL that's being fetched, which would help in test
debugging and to use switch construct, rather than nested if's.

While testing the change, I noticed some shifty loggin from the
exporter, so I fixed that as well while I was there.

* Continuation of the previous cleanups.

* Fix the issues with formatting by executing a grep

* and fix compilation error

* lowercase error

* fix the newly changed unit test
2019-01-18 14:33:32 -08:00