upgrade to latest dependencies (#1758)

bumping knative.dev/hack 3fdc50b...8f3c705:
  > 8f3c705 Update community files (# 247)
  > 62b15bd drop support for the istio add on flag (# 243)
  > f5be74f Update community files (# 245)
  > 80fd6da KO_DATA_PATH doesn't need to be set anymore (# 244)
  > 4b6bd86 Format go code (# 239)
  > 566898d Update community files (# 242)
  > 9d2ae47 Update community files (# 241)
  > cf1a127 🎁 Use Knative ls-tags tool (# 238)
bumping knative.dev/pkg 714b763...389f811:
  > 389f811 upgrade to latest dependencies (# 2629)
  > 918fd93 Update community files (# 2633)
  > 44d1d7d Go1.19 changes (# 2631)
  > 6718478 Update community files (# 2628)
  > dc1fae1 changeset: allow override the revision through ldflags (# 2601)
  > 92ed919 Fix: Mute the linter on error return values. (# 2627)
  > 8fa1a3f CmpOpts overrides should be passed through (# 2621)
  > 64fc3e5 ListPointer flag should also apply to filtered informers (# 2620)
  > 2f19491 Feature: Implement Apply codegen. (# 2624)
  > 6eb8f18 Update community files (# 2626)
  > 5cbee02 Filter reactor FieldErrors on validation to only error-level alerts. (# 2611)
  > 198b463 Cleanup: Turn multiple warnings into multiple warnings. (# 2619)
  > 728dfd8 Add FieldError#WrappedErrors to allow dependent code to have access (readonly) (# 2618)
  > 6ce976c Default observability config if nil (# 2614)
  > ff95684 make METRICS_DOMAIN optional when backend is not OpenCensus (# 2617)
  > b2a3a39 upgrade to latest dependencies (# 2616)
  > 9823d96 Update community files (# 2615)
  > 5dd89c6 Support istio *List types where Items is an array of pointer types (# 2613)
  > b812aff Support fetching observability from ctx. (# 2610)
bumping knative.dev/eventing 0fe923c...6de07e8:
  > 6de07e8 Update community files (# 6593)
  > a57c12f Update community files (# 6589)
  > cd98a61 upgrade to latest dependencies (# 6586)
  > 6ea012a Update community files (# 6588)
  > ecf7a29 upgrade to latest dependencies (# 6585)
  > cdb52cc upgrade to latest dependencies (# 6582)
  > 39c914b upgrade to latest dependencies (# 6580)
  > 47c2635 Update community files (# 6579)
  > 98dfb5b Doing base64 encode in channel's responseBody (# 6542)
bumping knative.dev/serving e82287d...1b38451:
  > 1b38451 Update net-gateway-api nightly (# 13444)
  > 09f44f5 Update community files (# 13434)
  > 6f42856 Update net-gateway-api nightly (# 13432)
  > d72ba07 bump kind to 1.17 in e2e (# 13437)
  > a47c428 ran codegen with go1.19 & fix linter warnings (# 13438)
  > bc368c3 Update net-contour nightly (# 13431)
  > 025c712 upgrade to latest dependencies (# 13429)
  > 3d9c724 upgrade to latest dependencies (# 13427)
  > 2ca1aea Update net-istio nightly (# 13428)
  > 41f35ca Update community files (# 13426)
  > c737bb1 Update net-certmanager nightly (# 13425)
  > 21fc2b2 upgrade to latest dependencies (# 13424)
  > 81ebd47 upgrade to latest dependencies (# 13423)
  > b44de34 Update net-gateway-api nightly (# 13422)
  > 3b35f78 Update net-contour nightly (# 13421)
  > 299aa96 upgrade to latest dependencies (# 13420)
  > 9e7150f upgrade to latest dependencies (# 13417)
  > 5411bd0 upgrade to latest dependencies (# 13415)
  > 4c99f48 Update community files (# 13413)
  > a6a18b8 updates HPA webhook api version (# 13411)
  > 0b88704 Update net-gateway-api nightly (# 13406)
bumping knative.dev/networking 58f3e62...0d4e937:
  > 0d4e937 upgrade to latest dependencies (# 731)
  > ed86031 Update community files (# 730)
  > dd3d3d7 Updates style/lint checks for go1.19 (# 733)
  > 7d97614 upgrade to latest dependencies (# 729)
  > e051f4e upgrade to latest dependencies (# 728)
  > 23d44c9 Update community files (# 727)
  > cb26aa7 upgrade to latest dependencies (# 726)
  > 0f6a54a upgrade to latest dependencies (# 725)
  > 2cbe3ef upgrade to latest dependencies (# 724)
  > 83b94f2 Update community files (# 723)
  > db966e7 fix http01 conformance tests (# 721)
  > fb5566f fix downstream tests (# 722)

Signed-off-by: Knative Automation <automation@knative.team>

Signed-off-by: Knative Automation <automation@knative.team>
This commit is contained in:
knative-automation 2022-11-07 14:53:22 +00:00 committed by GitHub
parent 2b347b1eca
commit daa3c65ab9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 299 additions and 222 deletions

10
go.mod
View File

@ -20,11 +20,11 @@ require (
k8s.io/cli-runtime v0.25.2 k8s.io/cli-runtime v0.25.2
k8s.io/client-go v0.25.2 k8s.io/client-go v0.25.2
k8s.io/code-generator v0.25.2 k8s.io/code-generator v0.25.2
knative.dev/eventing v0.35.0 knative.dev/eventing v0.35.1-0.20221104013907-6de07e818049
knative.dev/hack v0.0.0-20221010154335-3fdc50b9c24a knative.dev/hack v0.0.0-20221104013908-8f3c7050408b
knative.dev/networking v0.0.0-20221012062251-58f3e6239b4f knative.dev/networking v0.0.0-20221104155004-0d4e93709170
knative.dev/pkg v0.0.0-20221011175852-714b7630a836 knative.dev/pkg v0.0.0-20221104155204-389f811cea0a
knative.dev/serving v0.35.0 knative.dev/serving v0.35.1-0.20221107125622-1b38451a92f2
sigs.k8s.io/yaml v1.3.0 sigs.k8s.io/yaml v1.3.0
) )

20
go.sum
View File

@ -1089,16 +1089,16 @@ k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1 h1:MQ8BAZPZlWk3S9K4a9NCkI
k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1/go.mod h1:C/N6wCaBHeBHkHUesQOQy2/MZqGgMAFPqGsGQLdbZBU= k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1/go.mod h1:C/N6wCaBHeBHkHUesQOQy2/MZqGgMAFPqGsGQLdbZBU=
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed h1:jAne/RjBTyawwAy0utX5eqigAwz/lQhTmy+Hr/Cpue4= k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed h1:jAne/RjBTyawwAy0utX5eqigAwz/lQhTmy+Hr/Cpue4=
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA=
knative.dev/eventing v0.35.0 h1:0sn4Fc0OajdEf4s+0SucwzAIGvO3LZA/BZHsSwfjHes= knative.dev/eventing v0.35.1-0.20221104013907-6de07e818049 h1:JAbeKbn+3ZgD2PO+K3wZVJwcAlIkxFRCvKE+t9ui3Jo=
knative.dev/eventing v0.35.0/go.mod h1:MEqB5frQ5jQ2/A+WHpDU2VNLXum+4o7TiMhTdCvji9w= knative.dev/eventing v0.35.1-0.20221104013907-6de07e818049/go.mod h1:MUVPi3EN46i+13b0azAsZ09oevqd21RZzZPmRpUwwNo=
knative.dev/hack v0.0.0-20221010154335-3fdc50b9c24a h1:yfq1OMrkyYkxDeM0pmAOeN4YF16R/WG0C+VvLBeq4uc= knative.dev/hack v0.0.0-20221104013908-8f3c7050408b h1:EqqlOqjCy/hVexdmPpUjcplO2eZc12+jTdTpodfLaI4=
knative.dev/hack v0.0.0-20221010154335-3fdc50b9c24a/go.mod h1:yk2OjGDsbEnQjfxdm0/HJKS2WqTLEFg/N6nUs6Rqx3Q= knative.dev/hack v0.0.0-20221104013908-8f3c7050408b/go.mod h1:yk2OjGDsbEnQjfxdm0/HJKS2WqTLEFg/N6nUs6Rqx3Q=
knative.dev/networking v0.0.0-20221012062251-58f3e6239b4f h1:e/08+ofUjGjSYV2Usvb22IbkX4MjoiywbRtnXUK3FQY= knative.dev/networking v0.0.0-20221104155004-0d4e93709170 h1:/DP0jHUGFJcF20BH4waFLz/W/RBMH4f7wQpf12t0eDI=
knative.dev/networking v0.0.0-20221012062251-58f3e6239b4f/go.mod h1:GciicKYf4aWE138pT2ZKkZ/E10rd0Kt4ziX52A/HnVY= knative.dev/networking v0.0.0-20221104155004-0d4e93709170/go.mod h1:qwWlbknoGTz/NV+MKB7Hb2nMjwI5zfum3KLLSl2QUMc=
knative.dev/pkg v0.0.0-20221011175852-714b7630a836 h1:0N7Zo/O+xeUUebJPm9keBaGclrUoEbljr3J1MsqtaIM= knative.dev/pkg v0.0.0-20221104155204-389f811cea0a h1:mb0PB0FFD4ep9T2pmOJ089Ie9aviuCRrTWX26Egpvrs=
knative.dev/pkg v0.0.0-20221011175852-714b7630a836/go.mod h1:DMTRDJ5WRxf/DrlOPzohzfhSuJggscLZ8EavOq9O/x8= knative.dev/pkg v0.0.0-20221104155204-389f811cea0a/go.mod h1:JwNkOLWAeuMYlH9WQA83k+afGCanWcvWvdXZsI3xKo4=
knative.dev/serving v0.35.0 h1:t2hsXoa9+YLb7NkOeL6sPVYCPvpiVuy8YK7hbMVW1NU= knative.dev/serving v0.35.1-0.20221107125622-1b38451a92f2 h1:CY8DQUaej+EKqypQlQQoL56/4sImB+sMtRLvntpEExU=
knative.dev/serving v0.35.0/go.mod h1:eKvzlUmOFunHbVqkP5kmrNKSsjpo9TrYjWk/TK/4eGA= knative.dev/serving v0.35.1-0.20221107125622-1b38451a92f2/go.mod h1:+fo5a6d4Aw68JT5b39fcibyq9pWX6adcUvdjYhxeE1o=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=

View File

@ -149,9 +149,6 @@ This is a helper script for Knative E2E test scripts. To use it:
1. By default `knative_teardown()` and `test_teardown()` will be called after 1. By default `knative_teardown()` and `test_teardown()` will be called after
the tests finish, use `--skip-teardowns` if you don't want them to be called. the tests finish, use `--skip-teardowns` if you don't want them to be called.
1. By default Istio is installed on the cluster via Addon, use
`--skip-istio-addon` if you choose not to have it preinstalled.
1. By default Google Kubernetes Engine telemetry to Cloud Logging and Monitoring is disabled. 1. By default Google Kubernetes Engine telemetry to Cloud Logging and Monitoring is disabled.
This can be enabled by setting `ENABLE_GKE_TELEMETRY` to `true`. This can be enabled by setting `ENABLE_GKE_TELEMETRY` to `true`.

View File

@ -60,6 +60,7 @@ function setup_test_cluster() {
header "Setting up test cluster" header "Setting up test cluster"
kubectl get nodes kubectl get nodes
# Set the actual project the test cluster resides in # Set the actual project the test cluster resides in
# It will be a project assigned by Boskos if test is running on Prow, # It will be a project assigned by Boskos if test is running on Prow,
# otherwise will be ${E2E_GCP_PROJECT_ID} set up by user. # otherwise will be ${E2E_GCP_PROJECT_ID} set up by user.
@ -90,8 +91,6 @@ function setup_test_cluster() {
echo "- Cluster is ${k8s_cluster}" echo "- Cluster is ${k8s_cluster}"
echo "- Docker is ${KO_DOCKER_REPO}" echo "- Docker is ${KO_DOCKER_REPO}"
export KO_DATA_PATH="${REPO_ROOT_DIR}/.git"
# Do not run teardowns if we explicitly want to skip them. # Do not run teardowns if we explicitly want to skip them.
(( ! SKIP_TEARDOWNS )) && add_trap teardown_test_resources EXIT (( ! SKIP_TEARDOWNS )) && add_trap teardown_test_resources EXIT
@ -99,9 +98,6 @@ function setup_test_cluster() {
set +o errexit set +o errexit
set +o pipefail set +o pipefail
# Wait for Istio installation to complete, if necessary, before calling knative_setup.
# TODO(chizhg): is it really needed?
(( ! SKIP_ISTIO_ADDON )) && (wait_until_batch_job_complete istio-system || return 1)
if function_exists knative_setup; then if function_exists knative_setup; then
knative_setup || fail_test "Knative setup failed" knative_setup || fail_test "Knative setup failed"
fi fi
@ -131,7 +127,6 @@ function fail_test() {
} }
SKIP_TEARDOWNS=0 SKIP_TEARDOWNS=0
SKIP_ISTIO_ADDON=0
E2E_SCRIPT="" E2E_SCRIPT=""
CLOUD_PROVIDER="gke" CLOUD_PROVIDER="gke"
@ -171,8 +166,8 @@ function initialize() {
case ${parameter} in case ${parameter} in
--run-tests) run_tests=1 ;; --run-tests) run_tests=1 ;;
--skip-teardowns) SKIP_TEARDOWNS=1 ;; --skip-teardowns) SKIP_TEARDOWNS=1 ;;
# TODO(chizhg): remove this flag once the addons is defined as an env var. --skip-istio-addon) echo "--skip-istio-addon is no longer supported"
--skip-istio-addon) SKIP_ISTIO_ADDON=1 ;; ;; # This flag is a noop
*) *)
case ${parameter} in case ${parameter} in
--cloud-provider) shift; CLOUD_PROVIDER="$1" ;; --cloud-provider) shift; CLOUD_PROVIDER="$1" ;;
@ -185,11 +180,7 @@ function initialize() {
(( IS_PROW )) && [[ -z "${GCP_PROJECT_ID:-}" ]] && IS_BOSKOS=1 (( IS_PROW )) && [[ -z "${GCP_PROJECT_ID:-}" ]] && IS_BOSKOS=1
if [[ "${CLOUD_PROVIDER}" == "gke" ]]; then if [[ "${CLOUD_PROVIDER}" == "gke" ]]; then
if (( SKIP_ISTIO_ADDON )); then
custom_flags+=("--addons=NodeLocalDNS") custom_flags+=("--addons=NodeLocalDNS")
else
custom_flags+=("--addons=Istio,NodeLocalDNS")
fi
fi fi
readonly IS_BOSKOS readonly IS_BOSKOS

View File

@ -139,14 +139,7 @@ function __build_test_runner_for_module() {
# Don't merge these two lines, or return code will always be 0. # Don't merge these two lines, or return code will always be 0.
# Get all build tags in go code (ignore /vendor, /hack and /third_party) # Get all build tags in go code (ignore /vendor, /hack and /third_party)
local tags local tags
tags="$(grep -I -r '// +build' . | grep -v '/vendor/' | \ tags="$(go run knative.dev/test-infra/tools/go-ls-tags@latest --joiner=,)"
grep -v '/hack/' | \
grep -v '/third_party' | \
cut -f3 -d' ' | \
tr ',' '\n' | \
sort | uniq | \
grep -v '^!' | \
paste -s -d, /dev/stdin)"
local go_pkg_dirs local go_pkg_dirs
go_pkg_dirs="$(go list -tags "${tags}" ./...)" || return $? go_pkg_dirs="$(go list -tags "${tags}" ./...)" || return $?
if [[ -z "${go_pkg_dirs}" ]]; then if [[ -z "${go_pkg_dirs}" ]]; then

View File

@ -37,14 +37,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{
// AddToScheme adds all types of this clientset into the given scheme. This allows composition // AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in: // of clientsets, like in:
// //
// import ( // import (
// "k8s.io/client-go/kubernetes" // "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme" // clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// ) // )
// //
// kclientset, _ := kubernetes.NewForConfig(c) // kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
// //
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly. // correctly.

View File

@ -20,7 +20,7 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/url" "net/url"
"strings" "strings"
"text/template" "text/template"
@ -418,7 +418,7 @@ func checkTagTemplate(t *template.Template) error {
Name: "foo", Name: "foo",
Tag: "v2", Tag: "v2",
} }
return t.Execute(ioutil.Discard, data) return t.Execute(io.Discard, data)
} }
// asLabelSelector returns a LabelSelector extracted from a given configmap key. // asLabelSelector returns a LabelSelector extracted from a given configmap key.

View File

@ -31,10 +31,10 @@ type Populatable = ducktypes.Populatable
// the provided Implementable duck type. It is expected that under the resource // the provided Implementable duck type. It is expected that under the resource
// definition implementing a particular "Fooable" that one would write: // definition implementing a particular "Fooable" that one would write:
// //
// type ConcreteResource struct { ... } // type ConcreteResource struct { ... }
// //
// // Check that ConcreteResource properly implement Fooable. // // Check that ConcreteResource properly implement Fooable.
// err := duck.VerifyType(&ConcreteResource{}, &something.Fooable{}) // err := duck.VerifyType(&ConcreteResource{}, &something.Fooable{})
// //
// This will return an error if the duck typing is not satisfied. // This will return an error if the duck typing is not satisfied.
func VerifyType(instance interface{}, iface Implementable) error { func VerifyType(instance interface{}, iface Implementable) error {

View File

@ -83,11 +83,12 @@ var _ error = (*FieldError)(nil)
// ViaField is used to propagate a validation error along a field access. // ViaField is used to propagate a validation error along a field access.
// For example, if a type recursively validates its "spec" via: // For example, if a type recursively validates its "spec" via:
// if err := foo.Spec.Validate(); err != nil { //
// // Augment any field paths with the context that they were accessed // if err := foo.Spec.Validate(); err != nil {
// // via "spec". // // Augment any field paths with the context that they were accessed
// return err.ViaField("spec") // // via "spec".
// } // return err.ViaField("spec")
// }
func (fe *FieldError) ViaField(prefix ...string) *FieldError { func (fe *FieldError) ViaField(prefix ...string) *FieldError {
if fe == nil { if fe == nil {
return nil return nil
@ -114,11 +115,12 @@ func (fe *FieldError) ViaField(prefix ...string) *FieldError {
// ViaIndex is used to attach an index to the next ViaField provided. // ViaIndex is used to attach an index to the next ViaField provided.
// For example, if a type recursively validates a parameter that has a collection: // For example, if a type recursively validates a parameter that has a collection:
// for i, c := range spec.Collection { //
// if err := doValidation(c); err != nil { // for i, c := range spec.Collection {
// return err.ViaIndex(i).ViaField("collection") // if err := doValidation(c); err != nil {
// } // return err.ViaIndex(i).ViaField("collection")
// } // }
// }
func (fe *FieldError) ViaIndex(index int) *FieldError { func (fe *FieldError) ViaIndex(index int) *FieldError {
return fe.ViaField(asIndex(index)) return fe.ViaField(asIndex(index))
} }
@ -130,11 +132,12 @@ func (fe *FieldError) ViaFieldIndex(field string, index int) *FieldError {
// ViaKey is used to attach a key to the next ViaField provided. // ViaKey is used to attach a key to the next ViaField provided.
// For example, if a type recursively validates a parameter that has a collection: // For example, if a type recursively validates a parameter that has a collection:
// for k, v := range spec.Bag { //
// if err := doValidation(v); err != nil { // for k, v := range spec.Bag {
// return err.ViaKey(k).ViaField("bag") // if err := doValidation(v); err != nil {
// } // return err.ViaKey(k).ViaField("bag")
// } // }
// }
func (fe *FieldError) ViaKey(key string) *FieldError { func (fe *FieldError) ViaKey(key string) *FieldError {
return fe.ViaField(asKey(key)) return fe.ViaField(asKey(key))
} }
@ -145,7 +148,8 @@ func (fe *FieldError) ViaFieldKey(field, key string) *FieldError {
} }
// At is a way to alter the level of the diagnostics held in this FieldError. // At is a way to alter the level of the diagnostics held in this FieldError.
// ErrMissingField("foo").At(WarningLevel) //
// ErrMissingField("foo").At(WarningLevel)
func (fe *FieldError) At(l DiagnosticLevel) *FieldError { func (fe *FieldError) At(l DiagnosticLevel) *FieldError {
if fe == nil { if fe == nil {
return nil return nil
@ -166,9 +170,10 @@ func (fe *FieldError) At(l DiagnosticLevel) *FieldError {
} }
// Filter is a way to access the set of diagnostics having a particular level. // Filter is a way to access the set of diagnostics having a particular level.
// if err := x.Validate(ctx).Filter(ErrorLevel); err != nil { //
// return err // if err := x.Validate(ctx).Filter(ErrorLevel); err != nil {
// } // return err
// }
func (fe *FieldError) Filter(l DiagnosticLevel) *FieldError { func (fe *FieldError) Filter(l DiagnosticLevel) *FieldError {
if fe == nil { if fe == nil {
return nil return nil
@ -251,10 +256,15 @@ func (fe *FieldError) normalized() []*FieldError {
return errors return errors
} }
// WrappedErrors returns the value of the errors after normalizing and deduping using merge().
func (fe *FieldError) WrappedErrors() []*FieldError {
return merge(fe.normalized())
}
// Error implements error // Error implements error
func (fe *FieldError) Error() string { func (fe *FieldError) Error() string {
// Get the list of errors as a flat merged list. // Get the list of errors as a flat merged list.
normedErrors := merge(fe.normalized()) normedErrors := fe.WrappedErrors()
errs := make([]string, 0, len(normedErrors)) errs := make([]string, 0, len(normedErrors))
for _, e := range normedErrors { for _, e := range normedErrors {
if e.Details == "" { if e.Details == "" {
@ -282,10 +292,11 @@ func asKey(key string) string {
// flatten takes in a array of path components and looks for chances to flatten // flatten takes in a array of path components and looks for chances to flatten
// objects that have index prefixes, examples: // objects that have index prefixes, examples:
// err([0]).ViaField(bar).ViaField(foo) -> foo.bar.[0] converts to foo.bar[0] //
// err(bar).ViaIndex(0).ViaField(foo) -> foo.[0].bar converts to foo[0].bar // err([0]).ViaField(bar).ViaField(foo) -> foo.bar.[0] converts to foo.bar[0]
// err(bar).ViaField(foo).ViaIndex(0) -> [0].foo.bar converts to [0].foo.bar // err(bar).ViaIndex(0).ViaField(foo) -> foo.[0].bar converts to foo[0].bar
// err(bar).ViaIndex(0).ViaIndex(1).ViaField(foo) -> foo.[1].[0].bar converts to foo[1][0].bar // err(bar).ViaField(foo).ViaIndex(0) -> [0].foo.bar converts to [0].foo.bar
// err(bar).ViaIndex(0).ViaIndex(1).ViaField(foo) -> foo.[1].[0].bar converts to foo[1][0].bar
func flatten(path []string) string { func flatten(path []string) string {
var newPath []string var newPath []string
for _, part := range path { for _, part := range path {

View File

@ -39,7 +39,10 @@ var (
// The result will have a '-dirty' suffix if the workspace was not clean // The result will have a '-dirty' suffix if the workspace was not clean
func Get() string { func Get() string {
once.Do(func() { once.Do(func() {
rev = get() if rev == "" {
rev = get()
}
// It has been set through ldflags, do nothing
}) })
return rev return rev

View File

@ -29,6 +29,7 @@ type CustomArgs struct {
ExternalVersionsInformersPackage string ExternalVersionsInformersPackage string
ListersPackage string ListersPackage string
ForceKinds string ForceKinds string
ListerHasPointerElem bool
} }
// NewDefaults returns default arguments for the generator. // NewDefaults returns default arguments for the generator.
@ -45,6 +46,7 @@ func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&ca.ExternalVersionsInformersPackage, "external-versions-informers-package", ca.ExternalVersionsInformersPackage, "the full package name for the external versions injection informer to use") fs.StringVar(&ca.ExternalVersionsInformersPackage, "external-versions-informers-package", ca.ExternalVersionsInformersPackage, "the full package name for the external versions injection informer to use")
fs.StringVar(&ca.ListersPackage, "listers-package", ca.ListersPackage, "the full package name for client listers to use") fs.StringVar(&ca.ListersPackage, "listers-package", ca.ListersPackage, "the full package name for client listers to use")
fs.StringVar(&ca.ForceKinds, "force-genreconciler-kinds", ca.ForceKinds, `force kinds will override the genreconciler tag setting for the given set of kinds, comma separated: "Foo,Bar,Baz"`) fs.StringVar(&ca.ForceKinds, "force-genreconciler-kinds", ca.ForceKinds, `force kinds will override the genreconciler tag setting for the given set of kinds, comma separated: "Foo,Bar,Baz"`)
fs.BoolVar(&ca.ListerHasPointerElem, "lister-has-pointer-elem", ca.ListerHasPointerElem, "set to true if the List types have an Item array of pointer element types")
} }
// Validate checks the given arguments. // Validate checks the given arguments.

View File

@ -286,6 +286,11 @@ func (g *clientGenerator) GenerateType(c *generator.Context, t *types.Type, w io
"Group": group, "Group": group,
"VersionLower": version, "VersionLower": version,
"Kind": t.Name.Name, "Kind": t.Name.Name,
"ptrString": c.Universe.Function(types.Name{
Package: "knative.dev/pkg/ptr",
Name: "String",
}),
} }
for _, v := range verbs.List() { for _, v := range verbs.List() {
@ -575,13 +580,51 @@ func (w *wrap{{.GroupGoName}}{{.Version}}{{ .Type.Name.Name }}Impl) Patch(ctx {{
`, `,
"apply": `{{if .generateApply}} "apply": `{{if .generateApply}}
func (w *wrap{{.GroupGoName}}{{.Version}}{{ .Type.Name.Name }}Impl) Apply(ctx {{ .contextContext|raw }}, in *{{ .ApplyType|raw }}, opts {{ .metav1ApplyOptions|raw }}) (result *{{ .ResultType|raw }}, err error) { func (w *wrap{{.GroupGoName}}{{.Version}}{{ .Type.Name.Name }}Impl) Apply(ctx {{ .contextContext|raw }}, in *{{ .ApplyType|raw }}, opts {{ .metav1ApplyOptions|raw }}) (result *{{ .ResultType|raw }}, err error) {
panic("NYI") in.Kind = {{ .ptrString|raw }}("{{ .Kind }}")
{{ if .Group }}
in.APIVersion = {{ .ptrString|raw }}("{{ .Group }}/{{ .VersionLower }}")
{{ else }}
in.APIVersion = {{ .ptrString|raw }}("{{ .VersionLower }}")
{{ end }}
uo := &{{ .unstructuredUnstructured|raw }}{}
if err := convert(in, uo); err != nil {
return nil, err
}
uo, err = w.dyn{{if .Namespaced}}.Namespace(w.namespace){{end}}.Apply(ctx, uo.GetName(), uo, opts)
if err != nil {
return nil, err
}
out := &{{ .ResultType|raw }}{}
if err := convert(uo, out); err != nil {
return nil, err
}
return out, nil
} }
{{end}} {{end}}
`, `,
"applyStatus": `{{if .generateApply}} "applyStatus": `{{if .generateApply}}
func (w *wrap{{.GroupGoName}}{{.Version}}{{ .Type.Name.Name }}Impl) ApplyStatus(ctx {{ .contextContext|raw }}, in *{{ .ApplyType|raw }}, opts {{ .metav1ApplyOptions|raw }}) (result *{{ .ResultType|raw }}, err error) { func (w *wrap{{.GroupGoName}}{{.Version}}{{ .Type.Name.Name }}Impl) ApplyStatus(ctx {{ .contextContext|raw }}, in *{{ .ApplyType|raw }}, opts {{ .metav1ApplyOptions|raw }}) (result *{{ .ResultType|raw }}, err error) {
panic("NYI") in.Kind = {{ .ptrString|raw }}("{{ .Kind }}")
{{ if .Group }}
in.APIVersion = {{ .ptrString|raw }}("{{ .Group }}/{{ .VersionLower }}")
{{ else }}
in.APIVersion = {{ .ptrString|raw }}("{{ .VersionLower }}")
{{ end }}
uo := &{{ .unstructuredUnstructured|raw }}{}
if err := convert(in, uo); err != nil {
return nil, err
}
uo, err = w.dyn{{if .Namespaced}}.Namespace(w.namespace){{end}}.ApplyStatus(ctx, uo.GetName(), uo, opts)
if err != nil {
return nil, err
}
out := &{{ .ResultType|raw }}{}
if err := convert(uo, out); err != nil {
return nil, err
}
return out, nil
} }
{{end}} {{end}}
`, `,

View File

@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
@ -27,10 +27,10 @@ type CommentTag map[string][]string
// ExtractCommentTags parses comments for lines of the form: // ExtractCommentTags parses comments for lines of the form:
// //
// "marker" + "prefix" + ':' + "key=value,key2=value2". // "marker" + "prefix" + ':' + "key=value,key2=value2".
// //
// In the following example the marker is '+' and the prefix is 'foo': // In the following example the marker is '+' and the prefix is 'foo':
// +foo:key=value1,key2=value2,key=value3 // +foo:key=value1,key2=value2,key=value3
// //
// Values are optional; empty map is the default. A tag can be specified more than // Values are optional; empty map is the default. A tag can be specified more than
// one time and all values are returned. If the resulting map has an entry for // one time and all values are returned. If the resulting map has an entry for
@ -38,17 +38,19 @@ type CommentTag map[string][]string
// //
// Example: if you pass "+" for 'marker', and the following lines are in // Example: if you pass "+" for 'marker', and the following lines are in
// the comments: // the comments:
// +foo:key=value1,key2=value2,key=value3 //
// +bar // +foo:key=value1,key2=value2,key=value3
// +bar
// //
// Then this function will return: // Then this function will return:
// map[string]map[string]string{ //
// "foo":{ // map[string]map[string]string{
// "key": []string{"value1", "value3"}, // "foo":{
// "key2": []string{"value2"} // "key": []string{"value1", "value3"},
// }, // "key2": []string{"value2"}
// "bar": {}, // },
// } // "bar": {},
// }
// //
// Users are not expected to repeat values. // Users are not expected to repeat values.
func ExtractCommentTags(marker string, lines []string) CommentTags { func ExtractCommentTags(marker string, lines []string) CommentTags {

View File

@ -41,6 +41,7 @@ type filteredInjectionGenerator struct {
injectionClientSetPackage string injectionClientSetPackage string
clientSetPackage string clientSetPackage string
listerPkg string listerPkg string
listerHasPointerElem bool
} }
var _ generator.Generator = (*filteredInjectionGenerator)(nil) var _ generator.Generator = (*filteredInjectionGenerator)(nil)
@ -92,6 +93,7 @@ func (g *filteredInjectionGenerator) GenerateType(c *generator.Context, t *types
"clientSetInterface": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: "Interface"}), "clientSetInterface": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: "Interface"}),
"resourceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "Lister", Package: g.listerPkg}), "resourceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "Lister", Package: g.listerPkg}),
"resourceNamespaceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "NamespaceLister", Package: g.listerPkg}), "resourceNamespaceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "NamespaceLister", Package: g.listerPkg}),
"listerHasPointerElem": g.listerHasPointerElem,
"groupGoName": namer.IC(g.groupGoName), "groupGoName": namer.IC(g.groupGoName),
"versionGoName": namer.IC(g.groupVersion.Version.String()), "versionGoName": namer.IC(g.groupVersion.Version.String()),
"group": namer.IC(g.groupGoName), "group": namer.IC(g.groupGoName),
@ -246,7 +248,7 @@ func (w *wrapper) List(selector {{ .labelsSelector|raw }}) (ret []*{{ .type|raw
return nil, err return nil, err
} }
for idx := range lo.Items { for idx := range lo.Items {
ret = append(ret, &lo.Items[idx]) ret = append(ret, {{if not .listerHasPointerElem}}&{{end}}lo.Items[idx])
} }
return ret, nil return ret, nil
} }

View File

@ -41,6 +41,7 @@ type injectionGenerator struct {
injectionClientSetPackage string injectionClientSetPackage string
clientSetPackage string clientSetPackage string
listerPkg string listerPkg string
listerHasPointerElem bool
} }
var _ generator.Generator = (*injectionGenerator)(nil) var _ generator.Generator = (*injectionGenerator)(nil)
@ -92,6 +93,7 @@ func (g *injectionGenerator) GenerateType(c *generator.Context, t *types.Type, w
"clientSetInterface": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: "Interface"}), "clientSetInterface": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: "Interface"}),
"resourceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "Lister", Package: g.listerPkg}), "resourceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "Lister", Package: g.listerPkg}),
"resourceNamespaceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "NamespaceLister", Package: g.listerPkg}), "resourceNamespaceLister": c.Universe.Type(types.Name{Name: g.typeToGenerate.Name.Name + "NamespaceLister", Package: g.listerPkg}),
"listerHasPointerElem": g.listerHasPointerElem,
"groupGoName": namer.IC(g.groupGoName), "groupGoName": namer.IC(g.groupGoName),
"versionGoName": namer.IC(g.groupVersion.Version.String()), "versionGoName": namer.IC(g.groupVersion.Version.String()),
"group": g.groupVersion.Group.String(), "group": g.groupVersion.Group.String(),
@ -226,7 +228,7 @@ func (w *wrapper) List(selector {{ .labelsSelector|raw }}) (ret []*{{ .type|raw
return nil, err return nil, err
} }
for idx := range lo.Items { for idx := range lo.Items {
ret = append(ret, &lo.Items[idx]) ret = append(ret, {{if not .listerHasPointerElem}}&{{end}}lo.Items[idx])
} }
return ret, nil return ret, nil
} }

View File

@ -446,6 +446,7 @@ func versionInformerPackages(basePackage string, groupPkgName string, gv clientg
clientSetPackage: customArgs.VersionedClientSetPackage, clientSetPackage: customArgs.VersionedClientSetPackage,
injectionClientSetPackage: filepath.Join(basePackage, "client"), injectionClientSetPackage: filepath.Join(basePackage, "client"),
listerPkg: listerPackagePath, listerPkg: listerPackagePath,
listerHasPointerElem: customArgs.ListerHasPointerElem,
}) })
return generators return generators
}, },
@ -502,6 +503,7 @@ func versionInformerPackages(basePackage string, groupPkgName string, gv clientg
clientSetPackage: customArgs.VersionedClientSetPackage, clientSetPackage: customArgs.VersionedClientSetPackage,
injectionClientSetPackage: filepath.Join(basePackage, "client"), injectionClientSetPackage: filepath.Join(basePackage, "client"),
listerPkg: listerPackagePath, listerPkg: listerPackagePath,
listerHasPointerElem: customArgs.ListerHasPointerElem,
}) })
return generators return generators
}, },

View File

@ -16,6 +16,6 @@ limitations under the License.
// Package configmap exists to facilitate consuming Kubernetes ConfigMap // Package configmap exists to facilitate consuming Kubernetes ConfigMap
// resources in various ways, including: // resources in various ways, including:
// - Watching them for changes over time, and // - Watching them for changes over time, and
// - Loading them from a VolumeMount. // - Loading them from a VolumeMount.
package configmap package configmap

View File

@ -35,7 +35,7 @@ type Logger interface {
// Constructors is a map for specifying configmap names to // Constructors is a map for specifying configmap names to
// their function constructors // their function constructors
// //
// The values of this map must be functions with the definition // # The values of this map must be functions with the definition
// //
// func(*k8s.io/api/core/v1.ConfigMap) (... , error) // func(*k8s.io/api/core/v1.ConfigMap) (... , error)
// //
@ -60,7 +60,7 @@ type UntypedStore struct {
// NewUntypedStore creates an UntypedStore with given name, // NewUntypedStore creates an UntypedStore with given name,
// Logger and Constructors // Logger and Constructors
// //
// The Logger must not be nil // # The Logger must not be nil
// //
// The values in the Constructors map must be functions with // The values in the Constructors map must be functions with
// the definition // the definition

View File

@ -16,12 +16,12 @@ limitations under the License.
// Package hash contains various Knative specific hashing utilities. // Package hash contains various Knative specific hashing utilities.
// //
// - ChooseSubset is a consistent hashing/mapping function providing // - ChooseSubset is a consistent hashing/mapping function providing
// a consistent selection of N keys from M (N<=M) keys for a given // a consistent selection of N keys from M (N<=M) keys for a given
// target. // target.
// - BucketSet is a bucketer library which uses ChooseSubset under the // - BucketSet is a bucketer library which uses ChooseSubset under the
// the hood in order to implement consistent mapping between keys and // the hood in order to implement consistent mapping between keys and
// set of buckets, identified by unique names. Compared to basic bucket // set of buckets, identified by unique names. Compared to basic bucket
// implementation which just does hash%num_buckets, when the number of // implementation which just does hash%num_buckets, when the number of
// buckets change only a small subset of keys are supposed to migrate. // buckets change only a small subset of keys are supposed to migrate.
package hash package hash

View File

@ -22,84 +22,84 @@ limitations under the License.
// interesting. The first is in the context of implementations of // interesting. The first is in the context of implementations of
// `controller.Reconciler` being wrapped in a `*controller.Impl`: // `controller.Reconciler` being wrapped in a `*controller.Impl`:
// //
// import ( // import (
// // Simply linking this triggers the injection of the informer, which links // // Simply linking this triggers the injection of the informer, which links
// // the factory triggering its injection, and which links the client, // // the factory triggering its injection, and which links the client,
// // triggering its injection. All you need to know is that it works :) // // triggering its injection. All you need to know is that it works :)
// deployinformer "knative.dev/pkg/injection/informers/kubeinformers/appsv1/deployment" // deployinformer "knative.dev/pkg/injection/informers/kubeinformers/appsv1/deployment"
// "knative.dev/pkg/injection" // "knative.dev/pkg/injection"
// ) // )
// //
// func NewController(ctx context.Context) *controller.Impl { // func NewController(ctx context.Context) *controller.Impl {
// deploymentInformer := deployinformer.Get(ctx) // deploymentInformer := deployinformer.Get(ctx)
// // Pass deploymentInformer.Lister() to Reconciler // // Pass deploymentInformer.Lister() to Reconciler
// ... // ...
// // Set up events on deploymentInformer.Informer() // // Set up events on deploymentInformer.Informer()
// ... // ...
// } // }
// //
// Then in `package main` the entire controller process can be set up via: // Then in `package main` the entire controller process can be set up via:
// //
// package main // package main
// //
// import ( // import (
// // The set of controllers this controller process runs. // // The set of controllers this controller process runs.
// // Linking these will register their transitive dependencies, after // // Linking these will register their transitive dependencies, after
// // which the shared main can set up the rest. // // which the shared main can set up the rest.
// "github.com/knative/foo/pkg/reconciler/matt" // "github.com/knative/foo/pkg/reconciler/matt"
// "github.com/knative/foo/pkg/reconciler/scott" // "github.com/knative/foo/pkg/reconciler/scott"
// "github.com/knative/foo/pkg/reconciler/ville" // "github.com/knative/foo/pkg/reconciler/ville"
// "github.com/knative/foo/pkg/reconciler/dave" // "github.com/knative/foo/pkg/reconciler/dave"
// //
// // This defines the shared main for injected controllers. // // This defines the shared main for injected controllers.
// "knative.dev/pkg/injection/sharedmain" // "knative.dev/pkg/injection/sharedmain"
// ) // )
// //
// func main() { // func main() {
// sharedmain.Main("mycomponent", // sharedmain.Main("mycomponent",
// // We pass in the list of controllers to construct, and that's it! // // We pass in the list of controllers to construct, and that's it!
// // If we forget to add this, go will complain about the unused import. // // If we forget to add this, go will complain about the unused import.
// matt.NewController, // matt.NewController,
// scott.NewController, // scott.NewController,
// ville.NewController, // ville.NewController,
// dave.NewController, // dave.NewController,
// ) // )
// } // }
// //
// If you want to adapt the above to run the controller within a single // If you want to adapt the above to run the controller within a single
// namespace, you can instead do something like: // namespace, you can instead do something like:
// //
// package main // package main
// //
// import ( // import (
// // The set of controllers this controller process runs. // // The set of controllers this controller process runs.
// // Linking these will register their transitive dependencies, after // // Linking these will register their transitive dependencies, after
// // which the shared main can set up the rest. // // which the shared main can set up the rest.
// "github.com/knative/foo/pkg/reconciler/matt" // "github.com/knative/foo/pkg/reconciler/matt"
// "github.com/knative/foo/pkg/reconciler/scott" // "github.com/knative/foo/pkg/reconciler/scott"
// "github.com/knative/foo/pkg/reconciler/ville" // "github.com/knative/foo/pkg/reconciler/ville"
// "github.com/knative/foo/pkg/reconciler/dave" // "github.com/knative/foo/pkg/reconciler/dave"
// //
// // This defines the shared main for injected controllers. // // This defines the shared main for injected controllers.
// "knative.dev/pkg/injection/sharedmain" // "knative.dev/pkg/injection/sharedmain"
// //
// // These are used to set up the context. // // These are used to set up the context.
// "knative.dev/pkg/injection" // "knative.dev/pkg/injection"
// "knative.dev/pkg/signals" // "knative.dev/pkg/signals"
// ) // )
// //
// func main() { // func main() {
// // Scope the shared informer factories to the provided namespace. // // Scope the shared informer factories to the provided namespace.
// ctx := injection.WithNamespace(signals.NewContext(), "the-namespace") // ctx := injection.WithNamespace(signals.NewContext(), "the-namespace")
// //
// // Use our initial context when setting up the controllers. // // Use our initial context when setting up the controllers.
// sharedmain.MainWithContext(ctx, "mycomponent", // sharedmain.MainWithContext(ctx, "mycomponent",
// // We pass in the list of controllers to construct, and that's it! // // We pass in the list of controllers to construct, and that's it!
// // If we forget to add this, go will complain about the unused import. // // If we forget to add this, go will complain about the unused import.
// matt.NewController, // matt.NewController,
// scott.NewController, // scott.NewController,
// ville.NewController, // ville.NewController,
// dave.NewController, // dave.NewController,
// ) // )
// } // }
package injection package injection

View File

@ -34,9 +34,11 @@ import (
// //
// Typical integration: // Typical integration:
// ```go // ```go
// ctx, startInformers := injection.EnableInjectionOrDie(signals.NewContext(), nil) //
// ... start watches with informers, if required ... // ctx, startInformers := injection.EnableInjectionOrDie(signals.NewContext(), nil)
// startInformers() // ... start watches with informers, if required ...
// startInformers()
//
// ``` // ```
func EnableInjectionOrDie(ctx context.Context, cfg *rest.Config) (context.Context, func()) { func EnableInjectionOrDie(ctx context.Context, cfg *rest.Config) (context.Context, func()) {
if ctx == nil { if ctx == nil {

View File

@ -29,9 +29,12 @@ import (
// StringSet returns a marshaler for the set of strings. // StringSet returns a marshaler for the set of strings.
// To use this in sugared logger do: // To use this in sugared logger do:
//
// logger.Infow("Revision State", zap.Object("healthy", logging.StringSet(healthySet)), // logger.Infow("Revision State", zap.Object("healthy", logging.StringSet(healthySet)),
// zap.Object("unhealthy", logging.StringSet(unhealthySet))) // zap.Object("unhealthy", logging.StringSet(unhealthySet)))
//
// To use with non-sugared logger do: // To use with non-sugared logger do:
//
// logger.Info("Revision State", zap.Object("healthy", logging.StringSet(healthySet)), // logger.Info("Revision State", zap.Object("healthy", logging.StringSet(healthySet)),
// zap.Object("unhealthy", logging.StringSet(unhealthySet))) // zap.Object("unhealthy", logging.StringSet(unhealthySet)))
func StringSet(s sets.String) zapcore.ObjectMarshalerFunc { func StringSet(s sets.String) zapcore.ObjectMarshalerFunc {

View File

@ -124,12 +124,7 @@ func (mc *metricsConfig) record(ctx context.Context, mss []stats.Measurement, ro
func createMetricsConfig(_ context.Context, ops ExporterOptions) (*metricsConfig, error) { func createMetricsConfig(_ context.Context, ops ExporterOptions) (*metricsConfig, error) {
var mc metricsConfig var mc metricsConfig
if ops.Domain == "" {
return nil, errors.New("metrics domain cannot be empty")
}
mc.domain = ops.Domain mc.domain = ops.Domain
if ops.Component == "" { if ops.Component == "" {
return nil, errors.New("metrics component name cannot be empty") return nil, errors.New("metrics component name cannot be empty")
} }
@ -159,6 +154,9 @@ func createMetricsConfig(_ context.Context, ops ExporterOptions) (*metricsConfig
switch mc.backendDestination { switch mc.backendDestination {
case openCensus: case openCensus:
if ops.Domain == "" {
return nil, errors.New("metrics domain cannot be empty")
}
mc.collectorAddress = ops.ConfigMap[collectorAddressKey] mc.collectorAddress = ops.ConfigMap[collectorAddressKey]
if isSecure := ops.ConfigMap[collectorSecureKey]; isSecure != "" { if isSecure := ops.ConfigMap[collectorSecureKey]; isSecure != "" {
var err error var err error
@ -221,22 +219,7 @@ func Domain() string {
if domain := os.Getenv(DomainEnv); domain != "" { if domain := os.Getenv(DomainEnv); domain != "" {
return domain return domain
} }
return ""
panic(fmt.Sprintf(`The environment variable %q is not set
If this is a process running on Kubernetes, then it should be specifying
this via:
env:
- name: %s
value: knative.dev/some-repository
If this is a Go unit test consuming metric.Domain() then it should add the
following import:
import (
_ "knative.dev/pkg/metrics/testing"
)`, DomainEnv, DomainEnv))
} }
// prometheusPort returns the TCP port number configured via the environment // prometheusPort returns the TCP port number configured via the environment

View File

@ -17,8 +17,10 @@ limitations under the License.
package metrics package metrics
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"strconv"
texttemplate "text/template" texttemplate "text/template"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
@ -81,6 +83,22 @@ type ObservabilityConfig struct {
MetricsCollectorAddress string MetricsCollectorAddress string
} }
type ocfg struct{}
// WithConfig associates a observability configuration with the context.
func WithConfig(ctx context.Context, cfg *ObservabilityConfig) context.Context {
return context.WithValue(ctx, ocfg{}, cfg)
}
// GetObservability gets the observability config from the provided context.
func GetObservabilityConfig(ctx context.Context) *ObservabilityConfig {
untyped := ctx.Value(ocfg{})
if untyped == nil {
return nil
}
return untyped.(*ObservabilityConfig)
}
func defaultConfig() *ObservabilityConfig { func defaultConfig() *ObservabilityConfig {
return &ObservabilityConfig{ return &ObservabilityConfig{
LoggingURLTemplate: DefaultLogURLTemplate, LoggingURLTemplate: DefaultLogURLTemplate,
@ -92,6 +110,9 @@ func defaultConfig() *ObservabilityConfig {
// NewObservabilityConfigFromConfigMap creates a ObservabilityConfig from the supplied ConfigMap // NewObservabilityConfigFromConfigMap creates a ObservabilityConfig from the supplied ConfigMap
func NewObservabilityConfigFromConfigMap(configMap *corev1.ConfigMap) (*ObservabilityConfig, error) { func NewObservabilityConfigFromConfigMap(configMap *corev1.ConfigMap) (*ObservabilityConfig, error) {
oc := defaultConfig() oc := defaultConfig()
if configMap == nil {
return oc, nil
}
if err := cm.Parse(configMap.Data, if err := cm.Parse(configMap.Data,
cm.AsBool("logging.enable-var-log-collection", &oc.EnableVarLogCollection), cm.AsBool("logging.enable-var-log-collection", &oc.EnableVarLogCollection),
@ -120,6 +141,21 @@ func NewObservabilityConfigFromConfigMap(configMap *corev1.ConfigMap) (*Observab
return oc, nil return oc, nil
} }
func (oc *ObservabilityConfig) GetConfigMap() corev1.ConfigMap {
return corev1.ConfigMap{
Data: map[string]string{
"logging.enable-var-log-collection": strconv.FormatBool(oc.EnableVarLogCollection),
"logging.revision-url-template": oc.LoggingURLTemplate,
ReqLogTemplateKey: oc.RequestLogTemplate,
EnableReqLogKey: strconv.FormatBool(oc.EnableRequestLog),
EnableProbeReqLogKey: strconv.FormatBool(oc.EnableProbeRequestLog),
"metrics.request-metrics-backend-destination": oc.RequestMetricsBackend,
"profiling.enable": strconv.FormatBool(oc.EnableProfiling),
"metrics.opencensus-address": oc.MetricsCollectorAddress,
},
}
}
// ConfigMapName gets the name of the metrics ConfigMap // ConfigMapName gets the name of the metrics ConfigMap
func ConfigMapName() string { func ConfigMapName() string {
if cm := os.Getenv(configMapNameEnv); cm != "" { if cm := os.Getenv(configMapNameEnv); cm != "" {

View File

@ -41,7 +41,7 @@ func (emptyPromExporter) ExportView(viewData *view.Data) {
// a signal to enrich the internal Meters with Resource information. // a signal to enrich the internal Meters with Resource information.
} }
//nolint: unparam // False positive of flagging the second result of this function unused. // nolint: unparam // False positive of flagging the second result of this function unused.
func newPrometheusExporter(config *metricsConfig, logger *zap.SugaredLogger) (view.Exporter, ResourceExporterFactory, error) { func newPrometheusExporter(config *metricsConfig, logger *zap.SugaredLogger) (view.Exporter, ResourceExporterFactory, error) {
e, err := prom.NewExporter(prom.Options{Namespace: config.component}) e, err := prom.NewExporter(prom.Options{Namespace: config.component})
if err != nil { if err != nil {
@ -82,6 +82,7 @@ func startNewPromSrv(e *prom.Exporter, host string, port int) *http.Server {
if curPromSrv != nil { if curPromSrv != nil {
curPromSrv.Close() curPromSrv.Close()
} }
//nolint:gosec
curPromSrv = &http.Server{ curPromSrv = &http.Server{
Addr: host + ":" + strconv.Itoa(port), Addr: host + ":" + strconv.Itoa(port),
Handler: sm, Handler: sm,

View File

@ -28,6 +28,7 @@ import (
// NewServer returns a new HTTP Server with HTTP2 handler. // NewServer returns a new HTTP Server with HTTP2 handler.
func NewServer(addr string, h http.Handler) *http.Server { func NewServer(addr string, h http.Handler) *http.Server {
//nolint:gosec
h1s := &http.Server{ h1s := &http.Server{
Addr: addr, Addr: addr,
Handler: h2c.NewHandler(h, &http2.Server{}), Handler: h2c.NewHandler(h, &http2.Server{}),

View File

@ -110,6 +110,7 @@ func NewServer(handler http.Handler) *http.Server {
port = strconv.Itoa(ProfilingPort) port = strconv.Itoa(ProfilingPort)
} }
//nolint:gosec
return &http.Server{ return &http.Server{
Addr: ":" + port, Addr: ":" + port,
Handler: handler, Handler: handler,

View File

@ -5,7 +5,7 @@ Licensed under the Apache License, Veroute.on 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,

View File

@ -35,8 +35,10 @@ const (
// GetIngressEndpoint gets the ingress public IP or hostname. // GetIngressEndpoint gets the ingress public IP or hostname.
// address - is the endpoint to which we should actually connect. // address - is the endpoint to which we should actually connect.
// portMap - translates the request's port to the port on address to which the caller // portMap - translates the request's port to the port on address to which the caller
// should connect. This is used when the resolution to address goes through some //
// sort of port-mapping, e.g. Kubernetes node ports. // should connect. This is used when the resolution to address goes through some
// sort of port-mapping, e.g. Kubernetes node ports.
//
// err - an error when address/portMap cannot be established. // err - an error when address/portMap cannot be established.
func GetIngressEndpoint(ctx context.Context, kubeClientset kubernetes.Interface, endpointOverride string) (address string, portMap func(string) string, err error) { func GetIngressEndpoint(ctx context.Context, kubeClientset kubernetes.Interface, endpointOverride string) (address string, portMap func(string) string, err error) {
ingressName := istioIngressName ingressName := istioIngressName

View File

@ -33,9 +33,8 @@ This package exposes following methods:
A general flow for a Test Suite to use Zipkin Tracing support is as follows: A general flow for a Test Suite to use Zipkin Tracing support is as follows:
1. Call SetupZipkinTracing(kubernetes.Interface) in TestMain. 1. Call SetupZipkinTracing(kubernetes.Interface) in TestMain.
2. Use SpoofingClient to make HTTP requests. 2. Use SpoofingClient to make HTTP requests.
3. Call CleanupZipkinTracingSetup on cleanup after tests are executed. 3. Call CleanupZipkinTracingSetup on cleanup after tests are executed.
*/ */
package zipkin package zipkin

View File

@ -110,9 +110,10 @@ func SetupZipkinTracingFromConfigTracingOrFail(ctx context.Context, t testing.TB
} }
// SetupZipkinTracing sets up zipkin tracing which involves: // SetupZipkinTracing sets up zipkin tracing which involves:
// 1. Setting up port-forwarding from localhost to zipkin pod on the cluster // 1. Setting up port-forwarding from localhost to zipkin pod on the cluster
// (pid of the process doing Port-Forward is stored in a global variable). // (pid of the process doing Port-Forward is stored in a global variable).
// 2. Enable AlwaysSample config for tracing for the SpoofingClient. // 2. Enable AlwaysSample config for tracing for the SpoofingClient.
//
// The zipkin deployment must have the label app=zipkin // The zipkin deployment must have the label app=zipkin
func SetupZipkinTracing(ctx context.Context, kubeClientset kubernetes.Interface, logf logging.FormatLogger, zipkinRemotePort int, zipkinNamespace string) (err error) { func SetupZipkinTracing(ctx context.Context, kubeClientset kubernetes.Interface, logf logging.FormatLogger, zipkinRemotePort int, zipkinNamespace string) (err error) {
setupOnce.Do(func() { setupOnce.Do(func() {
@ -152,13 +153,13 @@ func SetupZipkinTracingOrFail(ctx context.Context, t testing.TB, kubeClientset k
// CleanupZipkinTracingSetup cleans up the Zipkin tracing setup on the machine. This involves killing the process performing port-forward. // CleanupZipkinTracingSetup cleans up the Zipkin tracing setup on the machine. This involves killing the process performing port-forward.
// This should be called exactly once in TestMain. Likely in the form: // This should be called exactly once in TestMain. Likely in the form:
// //
// func TestMain(m *testing.M) { // func TestMain(m *testing.M) {
// os.Exit(func() int { // os.Exit(func() int {
// // Any setup required for the tests. // // Any setup required for the tests.
// defer zipkin.CleanupZipkinTracingSetup(logger) // defer zipkin.CleanupZipkinTracingSetup(logger)
// return m.Run() // return m.Run()
// }()) // }())
// } // }
func CleanupZipkinTracingSetup(logf logging.FormatLogger) { func CleanupZipkinTracingSetup(logf logging.FormatLogger) {
teardownOnce.Do(func() { teardownOnce.Do(func() {
// Because CleanupZipkinTracingSetup only runs once, make sure that now that it has been // Because CleanupZipkinTracingSetup only runs once, make sure that now that it has been

View File

@ -43,14 +43,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{
// AddToScheme adds all types of this clientset into the given scheme. This allows composition // AddToScheme adds all types of this clientset into the given scheme. This allows composition
// of clientsets, like in: // of clientsets, like in:
// //
// import ( // import (
// "k8s.io/client-go/kubernetes" // "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kubernetes/scheme" // clientsetscheme "k8s.io/client-go/kubernetes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// ) // )
// //
// kclientset, _ := kubernetes.NewForConfig(c) // kclientset, _ := kubernetes.NewForConfig(c)
// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
// //
// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types
// correctly. // correctly.

10
vendor/modules.txt vendored
View File

@ -917,7 +917,7 @@ k8s.io/utils/net
k8s.io/utils/pointer k8s.io/utils/pointer
k8s.io/utils/strings/slices k8s.io/utils/strings/slices
k8s.io/utils/trace k8s.io/utils/trace
# knative.dev/eventing v0.35.0 # knative.dev/eventing v0.35.1-0.20221104013907-6de07e818049
## explicit; go 1.18 ## explicit; go 1.18
knative.dev/eventing/pkg/apis/config knative.dev/eventing/pkg/apis/config
knative.dev/eventing/pkg/apis/duck knative.dev/eventing/pkg/apis/duck
@ -945,10 +945,10 @@ knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1
knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1/fake
knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2 knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2
knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2/fake knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1beta2/fake
# knative.dev/hack v0.0.0-20221010154335-3fdc50b9c24a # knative.dev/hack v0.0.0-20221104013908-8f3c7050408b
## explicit; go 1.18 ## explicit; go 1.18
knative.dev/hack knative.dev/hack
# knative.dev/networking v0.0.0-20221012062251-58f3e6239b4f # knative.dev/networking v0.0.0-20221104155004-0d4e93709170
## explicit; go 1.18 ## explicit; go 1.18
knative.dev/networking/pkg knative.dev/networking/pkg
knative.dev/networking/pkg/apis/networking knative.dev/networking/pkg/apis/networking
@ -963,7 +963,7 @@ knative.dev/networking/pkg/http/probe
knative.dev/networking/pkg/http/proxy knative.dev/networking/pkg/http/proxy
knative.dev/networking/pkg/http/stats knative.dev/networking/pkg/http/stats
knative.dev/networking/pkg/k8s knative.dev/networking/pkg/k8s
# knative.dev/pkg v0.0.0-20221011175852-714b7630a836 # knative.dev/pkg v0.0.0-20221104155204-389f811cea0a
## explicit; go 1.18 ## explicit; go 1.18
knative.dev/pkg/apis knative.dev/pkg/apis
knative.dev/pkg/apis/duck knative.dev/pkg/apis/duck
@ -1013,7 +1013,7 @@ knative.dev/pkg/tracing/config
knative.dev/pkg/tracing/propagation knative.dev/pkg/tracing/propagation
knative.dev/pkg/tracing/propagation/tracecontextb3 knative.dev/pkg/tracing/propagation/tracecontextb3
knative.dev/pkg/tracker knative.dev/pkg/tracker
# knative.dev/serving v0.35.0 # knative.dev/serving v0.35.1-0.20221107125622-1b38451a92f2
## explicit; go 1.18 ## explicit; go 1.18
knative.dev/serving/pkg/apis/autoscaling knative.dev/serving/pkg/apis/autoscaling
knative.dev/serving/pkg/apis/autoscaling/v1alpha1 knative.dev/serving/pkg/apis/autoscaling/v1alpha1