Commit Graph

64 Commits

Author SHA1 Message Date
Matt Moore 0f78f8a8cc
Disable keep-alives on shutdown. (#1511)
See also: https://github.com/knative/pkg/issues/1509#issuecomment-659737054
2020-07-16 16:55:33 -07:00
Dave Protasowski caa444033b
use crd & webhook v1 APIs (#1391) 2020-06-19 08:43:25 -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
Victor Agababov 5ba6c1d101
Change %v to %w in errors and other nits (#1252)
* Change %v to %w in errors and other nits
Other are things I noticed when fixing the main %v->%w conversion

* fold
2020-04-27 15:04:51 -07:00
whaught d22642244e
Allow Unstructured callback from Validating Webhook (#1172)
* Add new callback pattern to pkg

* include the context

* typo

* Remove the empty instance of unstructured

* initialize the unstructured var

* Eliminate the unneeded pointer

* Pass a pointer to unstructured callback

* Create a validation specific context struct

* Move callback tests to own unit test case

* Switch from converting to decoding

* Update webhook/resourcesemantics/validation/validation.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* don't wrap context and include params

* split validation files

* include 2020 copyright

* include unit test for WithKubeClient

* Don't bother updating copyright date

* Inclue a unit test for panic

* Move dryRun to context

* Include context dry run unit test

* put the request operation in the context

* eliminate circular dep

* move kubeclient test out of context_test

* dont bother iterating callback map

* Callback takes a list of supported verbs

* Remove extra type

* Ensure Callback interface is public

* Alias Operation into validation

* alias Operation right in Webhook

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* correct parens

* minor style fixes

* Rename Callback to Func

* Fix build error

* Switch callback to take a list with a factory

* keep descriptive names

* update comment

* Drop pointer, correct comments

* Add a unit test to disallow duplicate verbs

* fix comments, struct{} for set

* switch to variadic arg for NewCallback

Co-authored-by: Victor Agababov <vagababov@gmail.com>
2020-04-06 12:22:19 -07:00
Matt Moore e2ee5bed78
Start the webhook before informers sync. (#1180)
* Start the webhook before informers sync.

Some webhooks (e.g. conversion) are required to list resources, so by delaying those until after informers have synced, we create a deadlock when they run in the same process.  This change has two key parts:
1. Start the webhook immediately when our process starts, and issue a callback from sharedmain when the informers have synced.
2. Block `Admit` calls until informers have synced (all conversions are exempt), unless they have been designated by implementing `webhook.StatelessAdmissionController`.

Our built-in admission controllers (defaulting, validation, configmap validation) have all been marked as stateless, the main case where we want to block `Admit` calls is when we require the informer to have synchronized to populate indices for Bindings.

* Add missing err declaration
2020-03-30 18:14:50 -07:00
Matt Moore 1893541a0f
Scope the webhook secret informers to the system namespace. (#1158) 2020-03-12 18:29:29 -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
Dave Protasowski cff115c2dd Refactor webhook to allow adding conversion support (#989)
* Refactor webhook to allow adding conversion support

* pr feedback

* fix memory leak

* We can use mux.Handle

* move admission integration tests to separate file
2020-01-20 09:20:05 -08:00
Slavomir Kaslev f890690397 De-race webhook integration tests (#938)
Webhook integration tests occasionally fail with on testgrid, e.g.
  https://prow.knative.dev/view/gcs/knative-prow/logs/ci-knative-pkg-continuous/1204193472353931264
  https://prow.knative.dev/view/gcs/knative-prow/logs/ci-knative-pkg-continuous/1203166664988823552

Fix this by waiting for all goroutines to finish before each test ends.
2019-12-13 06:59:54 -08:00
Matt Moore a55e24e80c Remove temporary logic to allow shared paths in webhook. (#943)
* Remove temporary logic to allow shared paths in webhook.

* Update webhook/webhook.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>
2019-12-12 11:14:52 -08:00
Matt Moore 4836f680bb Split the resource semantic webhooks into separate AdmissionControllers (#848)
By combining our validation logic into our mutating webhook we were previously allowing for mutating webhooks evaluated after our own to modify our resources into invalid shapes.  There are no guarantees around ordering of mutating webhooks (that I could find), so the only way to remedy this properly is to split apart the two into separate webhook configurations:
 - `defaulting`: which runs during the mutating admission webhook phase
 - `validation`: which runs during the validating admission webhook phase.

The diagram in [this post](https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/) is very helpful in illustrating the flow of webhooks.

Fixes: https://github.com/knative/pkg/issues/847
2019-11-14 16:51:02 -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
Nima Kaviani c39ee25c42 rename the variable for resource validation webhook (#653) 2019-09-11 06:40:29 -07:00
mattmoor-sockpuppet 014d54e62f golang format tools (#637)
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-09-06 07:26:05 -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
Victor Agababov 74c5d67ea0 Fix the issues pointed out by staticcheck (#541)
* Fix the issues pointed out by staticcheck

* review fix
2019-07-23 13:13:36 -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
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
Matt Moore 262650b2c0 Incorporate the sub-resource context into the context state populated by the webhook. (#442) 2019-06-05 20:36:39 -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
Matt Moore 2adf7f0c98 Add a few more general contexts built in serving. (#384)
Fix the user info annotation bug introduced along with the context stuff.

Fixes: https://github.com/knative/pkg/issues/383
2019-04-11 07:44:59 -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
Matt Moore 35d3a1b0d4 Modify the webhook to allow the use of duck types. (#323)
* Modify the webhook to allow the use of duck types.

This change enables us to define a duck type that applies to a whole class of GroupVersionKinds and leverage it to perform generic validation, defaulting, etc.

Fixes: #322

* Fix typo
2019-03-16 11:10:45 -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
Dave Protasowski 829b886f7e Don't close the http.Request body (#277)
As per net.http package for `http.Request.Body`

```
        // The Server will close the request body. The ServeHTTP
        // Handler does not need to.
```
2019-02-14 07:01:44 -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