Auto-update dependencies (#186)

Produced via:
  `dep ensure -update knative.dev/test-infra knative.dev/pkg`
/assign n3wscott
/cc n3wscott
This commit is contained in:
Matt Moore 2020-01-21 07:48:05 -08:00 committed by Knative Prow Robot
parent a1a620cc47
commit b404df2fb4
6 changed files with 218 additions and 101 deletions

6
Gopkg.lock generated
View File

@ -966,7 +966,7 @@
[[projects]]
branch = "master"
digest = "1:5321fe5a02c0f40e36f4bb8b962cfc09f3bb971e9058d06d59c9f421da43a65f"
digest = "1:342e150dd5c3ce921be78ce3e8cbfb03aaf01b07a26258f39dc9e90caf277a2b"
name = "knative.dev/pkg"
packages = [
"apis",
@ -985,7 +985,7 @@
"metrics/metricskey",
]
pruneopts = "T"
revision = "f609dc07e3a16e3278c1947c527a93269ed13957"
revision = "96d3b8c24c34ea7a8d9da9e7dbb65610aa9ac7b0"
[[projects]]
branch = "master"
@ -996,7 +996,7 @@
"tools/dep-collector",
]
pruneopts = "UT"
revision = "d5990f0e5a05d5819a40ad3b4de6227406850b48"
revision = "aebda4a107f44e1622e9770cdd64ebfb382e3e53"
[[projects]]
digest = "1:8730e0150dfb2b7e173890c8b9868e7a273082ef8e39f4940e3506a481cf895c"

View File

@ -95,6 +95,10 @@ func (testCase *TestCase) AddProperty(name, val string) {
// AddTestCase adds a testcase to the testsuite
func (ts *TestSuite) AddTestCase(tc TestCase) {
ts.Tests++
if tc.GetTestStatus() == Failed {
ts.Failures++
}
ts.TestCases = append(ts.TestCases, tc)
}

View File

@ -0,0 +1,22 @@
## junithelper
junithelper is a tool for creating a simple junit test result, which is used for
creating a single junit result file with a single test
## Usage
This tool can be invoked from command line with following parameters:
- `--suite`: name of suite
- `--name`: name of test
- `--err-msg`: (optional) error message, by default it's empty, means test
passed
- `--dest`: (optional) file path for result to be written to, default
`junit_result.xml`
### Example
```
go run junithelper --suite foo --name TestBar --err-msg "Failed Randomly" --dest
"/tmp/junit_important_suite.xml"
```

View File

@ -0,0 +1,57 @@
/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"io/ioutil"
"log"
"knative.dev/pkg/test/junit"
)
var (
suite string
name string
errMsg string
dest string
)
func main() {
flag.StringVar(&suite, "suite", "", "Name of suite")
flag.StringVar(&name, "name", "", "Name of test")
flag.StringVar(&errMsg, "err-msg", "", "Error message, empty means test passed, default empty")
flag.StringVar(&dest, "dest", "junit_result.xml", "Where junit xml writes to")
flag.Parse()
suites := junit.TestSuites{}
suite := junit.TestSuite{Name: suite}
var errP *string
if errMsg != "" {
errP = &errMsg
}
suite.AddTestCase(junit.TestCase{
Name: name,
Failure: errP,
})
suites.AddTestSuite(&suite)
contents, err := suites.ToBytes("", "")
if err != nil {
log.Fatal(err)
}
ioutil.WriteFile(dest, contents, 0644)
}

View File

@ -0,0 +1,94 @@
/*
Copyright 2020 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package webhook
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"go.uber.org/zap"
admissionv1beta1 "k8s.io/api/admission/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
)
// AdmissionController provides the interface for different admission controllers
type AdmissionController interface {
// Path returns the path that this particular admission controller serves on.
Path() string
// Admit is the callback which is invoked when an HTTPS request comes in on Path().
Admit(context.Context, *admissionv1beta1.AdmissionRequest) *admissionv1beta1.AdmissionResponse
}
// MakeErrorStatus creates an 'BadRequest' error AdmissionResponse
func MakeErrorStatus(reason string, args ...interface{}) *admissionv1beta1.AdmissionResponse {
result := apierrors.NewBadRequest(fmt.Sprintf(reason, args...)).Status()
return &admissionv1beta1.AdmissionResponse{
Result: &result,
Allowed: false,
}
}
func admissionHandler(rootLogger *zap.SugaredLogger, stats StatsReporter, c AdmissionController) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var ttStart = time.Now()
logger := rootLogger
logger.Infof("Webhook ServeHTTP request=%#v", r)
var review admissionv1beta1.AdmissionReview
if err := json.NewDecoder(r.Body).Decode(&review); err != nil {
http.Error(w, fmt.Sprintf("could not decode body: %v", err), http.StatusBadRequest)
return
}
logger = logger.With(
zap.String(logkey.Kind, review.Request.Kind.String()),
zap.String(logkey.Namespace, review.Request.Namespace),
zap.String(logkey.Name, review.Request.Name),
zap.String(logkey.Operation, string(review.Request.Operation)),
zap.String(logkey.Resource, review.Request.Resource.String()),
zap.String(logkey.SubResource, review.Request.SubResource),
zap.String(logkey.UserInfo, fmt.Sprint(review.Request.UserInfo)))
ctx := logging.WithLogger(r.Context(), logger)
var response admissionv1beta1.AdmissionReview
reviewResponse := c.Admit(ctx, review.Request)
logger.Infof("AdmissionReview for %#v: %s/%s response=%#v",
review.Request.Kind, review.Request.Namespace, review.Request.Name, reviewResponse)
if !reviewResponse.Allowed || reviewResponse.PatchType != nil || response.Response == nil {
response.Response = reviewResponse
}
response.Response.UID = review.Request.UID
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("could encode response: %v", err), http.StatusInternalServerError)
return
}
if stats != nil {
// Only report valid requests
stats.ReportRequest(review.Request, response.Response, time.Since(ttStart))
}
}
}

View File

@ -19,11 +19,9 @@ package webhook
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
// Injection stuff
kubeclient "knative.dev/pkg/client/injection/kube/client"
@ -31,12 +29,9 @@ import (
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
admissionv1beta1 "k8s.io/api/admission/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/kubernetes"
corelisters "k8s.io/client-go/listers/core/v1"
"knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
"knative.dev/pkg/system"
certresources "knative.dev/pkg/webhook/certificates/resources"
)
@ -63,30 +58,29 @@ type Options struct {
StatsReporter StatsReporter
}
// AdmissionController provides the interface for different admission controllers
type AdmissionController interface {
// Path returns the path that this particular admission controller serves on.
Path() string
// Admit is the callback which is invoked when an HTTPS request comes in on Path().
Admit(context.Context, *admissionv1beta1.AdmissionRequest) *admissionv1beta1.AdmissionResponse
}
// Webhook implements the external webhook for validation of
// resources and configuration.
type Webhook struct {
Client kubernetes.Interface
Options Options
Logger *zap.SugaredLogger
admissionControllers map[string]AdmissionController
secretlister corelisters.SecretLister
Client kubernetes.Interface
Options Options
Logger *zap.SugaredLogger
mux http.ServeMux
secretlister corelisters.SecretLister
}
// New constructs a Webhook
func New(
ctx context.Context,
admissionControllers []AdmissionController,
) (*Webhook, error) {
controllers []AdmissionController,
) (webhook *Webhook, err error) {
// ServeMux.Handle panics on duplicate paths
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error creating webhook %v", r)
}
}()
client := kubeclient.Get(ctx)
@ -111,35 +105,37 @@ func New(
opts.StatsReporter = reporter
}
// Build up a map of paths to admission controllers for routing handlers.
acs := make(map[string]AdmissionController, len(admissionControllers))
for _, ac := range admissionControllers {
if _, ok := acs[ac.Path()]; ok {
return nil, fmt.Errorf("duplicate webhook for path: %v", ac.Path())
}
acs[ac.Path()] = ac
webhook = &Webhook{
Client: client,
Options: *opts,
secretlister: secretInformer.Lister(),
Logger: logger,
}
return &Webhook{
Client: client,
Options: *opts,
secretlister: secretInformer.Lister(),
admissionControllers: acs,
Logger: logger,
}, nil
webhook.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("no admission controller registered for: %s", r.URL.Path), http.StatusBadRequest)
})
for _, c := range controllers {
webhook.mux.Handle(
c.Path(),
admissionHandler(logger, opts.StatsReporter, c),
)
}
return
}
// Run implements the admission controller run loop.
func (ac *Webhook) Run(stop <-chan struct{}) error {
logger := ac.Logger
func (wh *Webhook) Run(stop <-chan struct{}) error {
logger := wh.Logger
ctx := logging.WithLogger(context.Background(), logger)
server := &http.Server{
Handler: ac,
Addr: fmt.Sprintf(":%v", ac.Options.Port),
Handler: wh,
Addr: fmt.Sprintf(":%d", wh.Options.Port),
TLSConfig: &tls.Config{
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
secret, err := ac.secretlister.Secrets(system.Namespace()).Get(ac.Options.SecretName)
secret, err := wh.secretlister.Secrets(system.Namespace()).Get(wh.Options.SecretName)
if err != nil {
return nil, err
}
@ -183,13 +179,7 @@ func (ac *Webhook) Run(stop <-chan struct{}) error {
}
}
// ServeHTTP implements the external admission webhook for mutating
// serving resources.
func (ac *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var ttStart = time.Now()
logger := ac.Logger
logger.Infof("Webhook ServeHTTP request=%#v", r)
func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Verify the content type is accurate.
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
@ -197,55 +187,5 @@ func (ac *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
var review admissionv1beta1.AdmissionReview
if err := json.NewDecoder(r.Body).Decode(&review); err != nil {
http.Error(w, fmt.Sprintf("could not decode body: %v", err), http.StatusBadRequest)
return
}
logger = logger.With(
zap.String(logkey.Kind, fmt.Sprint(review.Request.Kind)),
zap.String(logkey.Namespace, review.Request.Namespace),
zap.String(logkey.Name, review.Request.Name),
zap.String(logkey.Operation, fmt.Sprint(review.Request.Operation)),
zap.String(logkey.Resource, fmt.Sprint(review.Request.Resource)),
zap.String(logkey.SubResource, fmt.Sprint(review.Request.SubResource)),
zap.String(logkey.UserInfo, fmt.Sprint(review.Request.UserInfo)))
ctx := logging.WithLogger(r.Context(), logger)
c, ok := ac.admissionControllers[r.URL.Path]
if !ok {
http.Error(w, fmt.Sprintf("no admission controller registered for: %s", r.URL.Path), http.StatusBadRequest)
return
}
var response admissionv1beta1.AdmissionReview
reviewResponse := c.Admit(ctx, review.Request)
logger.Infof("AdmissionReview for %#v: %s/%s response=%#v",
review.Request.Kind, review.Request.Namespace, review.Request.Name, reviewResponse)
if !reviewResponse.Allowed {
response.Response = reviewResponse
} else if reviewResponse.PatchType != nil || response.Response == nil {
response.Response = reviewResponse
}
response.Response.UID = review.Request.UID
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("could encode response: %v", err), http.StatusInternalServerError)
return
}
if ac.Options.StatsReporter != nil {
// Only report valid requests
ac.Options.StatsReporter.ReportRequest(review.Request, response.Response, time.Since(ttStart))
}
}
func MakeErrorStatus(reason string, args ...interface{}) *admissionv1beta1.AdmissionResponse {
result := apierrors.NewBadRequest(fmt.Sprintf(reason, args...)).Status()
return &admissionv1beta1.AdmissionResponse{
Result: &result,
Allowed: false,
}
wh.mux.ServeHTTP(w, r)
}