From dd77e728007d9284ed9d6c106d4d196c0c8fc2fe Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 May 2025 11:20:01 +0000 Subject: [PATCH] rebase: bump the k8s-dependencies group in /e2e with 3 updates Bumps the k8s-dependencies group in /e2e with 3 updates: [k8s.io/apimachinery](https://github.com/kubernetes/apimachinery), [k8s.io/cloud-provider](https://github.com/kubernetes/cloud-provider) and [k8s.io/pod-security-admission](https://github.com/kubernetes/pod-security-admission). Updates `k8s.io/apimachinery` from 0.32.3 to 0.33.0 - [Commits](https://github.com/kubernetes/apimachinery/compare/v0.32.3...v0.33.0) Updates `k8s.io/cloud-provider` from 0.32.3 to 0.33.0 - [Commits](https://github.com/kubernetes/cloud-provider/compare/v0.32.3...v0.33.0) Updates `k8s.io/pod-security-admission` from 0.32.3 to 0.33.0 - [Commits](https://github.com/kubernetes/pod-security-admission/compare/v0.32.3...v0.33.0) --- updated-dependencies: - dependency-name: k8s.io/apimachinery dependency-version: 0.33.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s-dependencies - dependency-name: k8s.io/cloud-provider dependency-version: 0.33.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s-dependencies - dependency-name: k8s.io/pod-security-admission dependency-version: 0.33.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: k8s-dependencies ... Signed-off-by: dependabot[bot] --- e2e/go.mod | 60 +- e2e/go.sum | 129 +- e2e/vendor/cel.dev/expr/README.md | 2 - .../asaskevich/govalidator/.travis.yml | 14 - .../asaskevich/govalidator/CONTRIBUTING.md | 63 - .../github.com/asaskevich/govalidator/LICENSE | 21 - .../asaskevich/govalidator/README.md | 507 -- .../asaskevich/govalidator/arrays.go | 58 - .../asaskevich/govalidator/converter.go | 64 - .../asaskevich/govalidator/error.go | 43 - .../asaskevich/govalidator/numerics.go | 97 - .../asaskevich/govalidator/patterns.go | 101 - .../asaskevich/govalidator/types.go | 636 --- .../asaskevich/govalidator/utils.go | 270 - .../asaskevich/govalidator/validator.go | 1278 ----- .../asaskevich/govalidator/wercker.yml | 15 - .../github.com/google/cel-go/cel/env.go | 10 +- .../github.com/google/cel-go/cel/inlining.go | 2 +- e2e/vendor/github.com/google/cel-go/cel/io.go | 14 +- .../github.com/google/cel-go/cel/library.go | 112 +- .../github.com/google/cel-go/cel/optimizer.go | 6 +- .../github.com/google/cel-go/cel/options.go | 18 + .../github.com/google/cel-go/cel/program.go | 3 + .../google/cel-go/checker/checker.go | 6 + .../github.com/google/cel-go/checker/cost.go | 654 ++- .../google/cel-go/common/ast/factory.go | 29 +- .../google/cel-go/common/debug/debug.go | 2 +- .../google/cel-go/common/decls/decls.go | 10 + .../github.com/google/cel-go/common/errors.go | 11 +- .../google/cel-go/common/types/err.go | 6 + .../google/cel-go/common/types/list.go | 4 +- .../google/cel-go/common/types/object.go | 2 +- .../google/cel-go/common/types/types.go | 13 + .../github.com/google/cel-go/ext/BUILD.bazel | 5 +- .../github.com/google/cel-go/ext/README.md | 34 +- .../google/cel-go/ext/comprehensions.go | 58 +- .../github.com/google/cel-go/ext/encoders.go | 30 +- .../google/cel-go/ext/formatting.go | 2 +- .../github.com/google/cel-go/ext/guards.go | 8 +- .../github.com/google/cel-go/ext/lists.go | 37 +- .../github.com/google/cel-go/ext/native.go | 20 +- .../github.com/google/cel-go/ext/protos.go | 25 +- .../github.com/google/cel-go/ext/sets.go | 23 +- .../google/cel-go/interpreter/activation.go | 22 + .../cel-go/interpreter/attribute_patterns.go | 13 +- .../cel-go/interpreter/interpretable.go | 42 +- .../google/cel-go/interpreter/planner.go | 10 +- .../google/cel-go/interpreter/prune.go | 63 +- .../google/cel-go/interpreter/runtimecost.go | 28 +- .../github.com/google/cel-go/parser/errors.go | 6 +- .../google/cel-go/parser/gen/CEL.g4 | 13 +- .../google/cel-go/parser/gen/CEL.interp | 5 +- .../google/cel-go/parser/gen/CEL.tokens | 1 + .../google/cel-go/parser/gen/CELLexer.interp | 5 +- .../google/cel-go/parser/gen/CELLexer.tokens | 1 + .../cel-go/parser/gen/cel_base_listener.go | 28 +- .../cel-go/parser/gen/cel_base_visitor.go | 17 +- .../google/cel-go/parser/gen/cel_lexer.go | 595 +-- .../google/cel-go/parser/gen/cel_listener.go | 29 +- .../google/cel-go/parser/gen/cel_parser.go | 2367 +++++---- .../google/cel-go/parser/gen/cel_visitor.go | 19 +- .../github.com/google/cel-go/parser/helper.go | 5 + .../github.com/google/cel-go/parser/macro.go | 32 +- .../google/cel-go/parser/options.go | 23 + .../github.com/google/cel-go/parser/parser.go | 85 +- .../google/cel-go/parser/unescape.go | 42 +- .../google/cel-go/parser/unparser.go | 42 +- .../github.com/google/gofuzz/.travis.yml | 10 - .../github.com/google/gofuzz/CONTRIBUTING.md | 67 - e2e/vendor/github.com/google/gofuzz/doc.go | 18 - e2e/vendor/github.com/google/gofuzz/fuzz.go | 605 --- .../github.com/gorilla/websocket/README.md | 17 +- .../github.com/gorilla/websocket/client.go | 245 +- .../gorilla/websocket/compression.go | 6 +- .../github.com/gorilla/websocket/conn.go | 112 +- .../github.com/gorilla/websocket/proxy.go | 53 +- .../github.com/gorilla/websocket/server.go | 124 +- .../gorilla/websocket/tls_handshake.go | 21 - .../gorilla/websocket/tls_handshake_116.go | 21 - .../github.com/gorilla/websocket/util.go | 15 + .../gorilla/websocket/x_net_proxy.go | 473 -- .../grpc-gateway/v2/runtime/BUILD.bazel | 2 +- .../grpc-gateway/v2/runtime/context.go | 11 + .../grpc-gateway/v2/runtime/convert.go | 6 +- .../grpc-gateway/v2/runtime/errors.go | 31 +- .../grpc-gateway/v2/runtime/fieldmask.go | 2 +- .../grpc-gateway/v2/runtime/handler.go | 40 +- .../grpc-gateway/v2/runtime/marshaler.go | 8 + .../v2/runtime/marshaler_registry.go | 4 +- .../grpc-gateway/v2/runtime/mux.go | 69 +- .../grpc-gateway/v2/runtime/proto2_convert.go | 4 +- .../grpc-gateway/v2/runtime/query.go | 6 +- .../grpc-gateway/v2/utilities/pattern.go | 2 +- .../v2/utilities/string_array_flag.go | 2 +- .../go.etcd.io/etcd/api/v3/version/version.go | 2 +- .../go.etcd.io/etcd/client/v3/README.md | 7 - e2e/vendor/go.etcd.io/etcd/client/v3/lease.go | 12 +- .../net/http/otelhttp/client.go | 6 +- .../net/http/otelhttp/common.go | 14 - .../net/http/otelhttp/config.go | 15 +- .../net/http/otelhttp/handler.go | 108 +- .../otelhttp/internal/request/body_wrapper.go | 75 + .../internal/request/resp_writer_wrapper.go | 119 + .../net/http/otelhttp/internal/semconv/env.go | 179 +- .../otelhttp/internal/semconv/httpconv.go | 348 ++ .../http/otelhttp/internal/semconv/util.go | 15 +- .../http/otelhttp/internal/semconv/v1.20.0.go | 208 +- .../http/otelhttp/internal/semconv/v1.24.0.go | 197 - .../otelhttp/internal/semconvutil/netconv.go | 2 +- .../net/http/otelhttp/start_time_context.go | 29 + .../net/http/otelhttp/transport.go | 106 +- .../net/http/otelhttp/version.go | 2 +- .../instrumentation/net/http/otelhttp/wrap.go | 99 - .../tracetransform/instrumentation.go | 5 +- .../otlptrace/internal/tracetransform/span.go | 30 +- .../otlp/otlptrace/otlptracegrpc/client.go | 7 +- .../otlp/otlptrace/otlptracegrpc/doc.go | 5 +- .../internal/envconfig/envconfig.go | 32 +- .../internal/otlpconfig/options.go | 8 +- .../otlptracegrpc/internal/retry/retry.go | 2 +- .../otlp/otlptrace/otlptracegrpc/options.go | 10 +- .../otel/exporters/otlp/otlptrace/version.go | 2 +- .../otel/semconv/v1.24.0/README.md | 3 - .../otel/semconv/v1.24.0/attribute_group.go | 4387 ----------------- .../otel/semconv/v1.24.0/doc.go | 9 - .../otel/semconv/v1.24.0/event.go | 200 - .../otel/semconv/v1.24.0/exception.go | 9 - .../otel/semconv/v1.24.0/metric.go | 1071 ---- .../otel/semconv/v1.24.0/resource.go | 2545 ---------- .../otel/semconv/v1.24.0/schema.go | 9 - .../otel/semconv/v1.24.0/trace.go | 1323 ----- .../googleapis/api/annotations/client.pb.go | 292 +- .../googleapis/api/annotations/http.pb.go | 6 +- .../googleapis/api/annotations/resource.pb.go | 5 +- .../googleapis/api/annotations/routing.pb.go | 2 +- .../grpc/balancer/base/balancer.go | 12 +- .../endpointsharding/endpointsharding.go | 20 +- .../pickfirst/pickfirstleaf/pickfirstleaf.go | 43 +- .../grpc_binarylog_v1/binarylog.pb.go | 2 +- .../google.golang.org/grpc/clientconn.go | 3 +- .../grpc/health/grpc_health_v1/health.pb.go | 167 +- .../health/grpc_health_v1/health_grpc.pb.go | 64 +- .../grpc/internal/envconfig/envconfig.go | 20 +- .../grpc/internal/internal.go | 13 + .../grpc/internal/metadata/metadata.go | 26 +- .../grpc/internal/transport/client_stream.go | 2 +- .../grpc/internal/transport/http2_client.go | 3 +- .../grpc/internal/transport/http2_server.go | 23 +- .../grpc/internal/transport/server_stream.go | 6 +- .../grpc/resolver/manual/manual.go | 34 +- .../google.golang.org/grpc/resolver/map.go | 81 +- .../google.golang.org/grpc/stats/stats.go | 35 +- e2e/vendor/google.golang.org/grpc/version.go | 2 +- .../k8s.io/apimachinery/pkg/api/errors/doc.go | 2 +- .../k8s.io/apimachinery/pkg/api/meta/doc.go | 2 +- .../k8s.io/apimachinery/pkg/api/meta/help.go | 3 + .../pkg/api/operation/operation.go | 56 + .../apimachinery/pkg/api/validation/doc.go | 2 +- .../pkg/api/validation/generic.go | 2 +- .../k8s.io/apimachinery/pkg/apis/asn1/oid.go | 43 + .../pkg/apis/meta/internalversion/doc.go | 2 +- .../apis/meta/internalversion/scheme/doc.go | 2 +- .../pkg/apis/meta/internalversion/types.go | 2 - .../apimachinery/pkg/apis/meta/v1/doc.go | 2 +- .../pkg/apis/meta/v1/micro_time_fuzz.go | 13 +- .../pkg/apis/meta/v1/time_fuzz.go | 13 +- .../pkg/apis/meta/v1/unstructured/helpers.go | 31 +- .../apis/meta/v1/unstructured/unstructured.go | 4 +- .../pkg/apis/meta/v1/validation/validation.go | 2 +- .../apimachinery/pkg/apis/meta/v1beta1/doc.go | 2 +- .../k8s.io/apimachinery/pkg/conversion/doc.go | 2 +- .../pkg/conversion/queryparams/doc.go | 2 +- .../k8s.io/apimachinery/pkg/fields/doc.go | 2 +- .../k8s.io/apimachinery/pkg/labels/doc.go | 2 +- .../k8s.io/apimachinery/pkg/runtime/doc.go | 2 +- .../apimachinery/pkg/runtime/interfaces.go | 1 + .../k8s.io/apimachinery/pkg/runtime/scheme.go | 39 + .../serializer/cbor/internal/modes/custom.go | 4 +- .../pkg/runtime/serializer/codec_factory.go | 23 +- .../runtime/serializer/json/collections.go | 230 + .../pkg/runtime/serializer/json/json.go | 16 +- .../serializer/protobuf/collections.go | 174 + .../pkg/runtime/serializer/protobuf/doc.go | 2 +- .../runtime/serializer/protobuf/protobuf.go | 87 +- .../apimachinery/pkg/runtime/types_proto.go | 127 +- .../k8s.io/apimachinery/pkg/types/doc.go | 2 +- .../k8s.io/apimachinery/pkg/util/diff/diff.go | 2 +- .../apimachinery/pkg/util/errors/doc.go | 2 +- .../apimachinery/pkg/util/framer/framer.go | 6 +- .../apimachinery/pkg/util/httpstream/doc.go | 2 +- .../pkg/util/httpstream/wsstream/doc.go | 2 +- .../pkg/util/intstr/instr_fuzz.go | 14 +- .../k8s.io/apimachinery/pkg/util/proxy/doc.go | 2 +- .../apimachinery/pkg/util/runtime/runtime.go | 46 +- .../k8s.io/apimachinery/pkg/util/sets/doc.go | 2 +- .../util/validation/field/error_matcher.go | 212 + .../pkg/util/validation/field/errors.go | 132 +- .../apimachinery/pkg/util/validation/ip.go | 278 ++ .../pkg/util/validation/validation.go | 40 - .../apimachinery/pkg/util/version/doc.go | 2 +- .../apimachinery/pkg/util/version/version.go | 18 +- .../apimachinery/pkg/util/wait/backoff.go | 50 +- .../k8s.io/apimachinery/pkg/util/wait/doc.go | 2 +- .../k8s.io/apimachinery/pkg/util/wait/loop.go | 4 +- .../k8s.io/apimachinery/pkg/util/wait/wait.go | 9 +- .../apimachinery/pkg/util/waitgroup/doc.go | 2 +- .../apimachinery/pkg/util/yaml/decoder.go | 163 +- .../pkg/util/yaml/stream_reader.go | 130 + .../k8s.io/apimachinery/pkg/version/doc.go | 4 +- .../k8s.io/apimachinery/pkg/version/types.go | 28 +- .../k8s.io/apimachinery/pkg/watch/doc.go | 2 +- .../apimachinery/pkg/watch/streamwatcher.go | 15 +- .../k8s.io/apimachinery/pkg/watch/watch.go | 37 +- .../config/apis/webhookadmission/doc.go | 2 +- .../config/apis/webhookadmission/v1/doc.go | 2 +- .../apis/webhookadmission/v1alpha1/doc.go | 2 +- .../admission/plugin/webhook/errors/doc.go | 2 +- .../admission/plugin/webhook/mutating/doc.go | 2 +- .../webhook/predicates/namespace/doc.go | 2 +- .../plugin/webhook/predicates/object/doc.go | 2 +- .../admission/plugin/webhook/request/doc.go | 2 +- .../plugin/webhook/validating/doc.go | 2 +- .../apiserver/pkg/apis/apidiscovery/v2/doc.go | 2 +- .../apiserver/pkg/apis/apiserver/doc.go | 2 +- .../apiserver/pkg/apis/apiserver/v1/doc.go | 2 +- .../pkg/apis/apiserver/v1alpha1/doc.go | 2 +- .../pkg/apis/apiserver/v1alpha1/types.go | 4 +- .../pkg/apis/apiserver/v1beta1/doc.go | 2 +- .../pkg/apis/apiserver/v1beta1/types.go | 4 +- .../k8s.io/apiserver/pkg/apis/audit/doc.go | 2 +- .../k8s.io/apiserver/pkg/apis/audit/v1/doc.go | 2 +- .../pkg/authentication/request/x509/doc.go | 2 +- .../pkg/authentication/request/x509/x509.go | 39 + .../apiserver/pkg/authentication/user/doc.go | 2 +- .../apiserver/pkg/authorization/path/doc.go | 2 +- .../apiserver/pkg/cel/environment/base.go | 17 +- .../k8s.io/apiserver/pkg/cel/library/cidr.go | 7 +- .../k8s.io/apiserver/pkg/cel/library/cost.go | 11 +- .../apiserver/pkg/cel/library/format.go | 12 +- .../k8s.io/apiserver/pkg/cel/library/ip.go | 4 +- .../apiserver/pkg/cel/library/semverlib.go | 115 +- .../endpoints/discovery/aggregated/fake.go | 2 +- .../endpoints/discovery/aggregated/handler.go | 10 + .../discovery/aggregated/negotiation.go | 6 + .../endpoints/discovery/aggregated/wrapper.go | 14 +- .../k8s.io/apiserver/pkg/endpoints/doc.go | 2 +- .../pkg/endpoints/filters/authentication.go | 2 +- .../pkg/endpoints/filters/authorization.go | 1 + .../apiserver/pkg/endpoints/filters/doc.go | 2 +- .../apiserver/pkg/endpoints/filters/traces.go | 19 +- .../apiserver/pkg/endpoints/handlers/doc.go | 2 +- .../pkg/endpoints/handlers/negotiation/doc.go | 2 +- .../endpoints/handlers/responsewriters/doc.go | 2 +- .../handlers/responsewriters/writers.go | 106 +- .../apiserver/pkg/endpoints/request/doc.go | 2 +- .../pkg/endpoints/request/webhook_duration.go | 32 + .../apiserver/pkg/features/kube_features.go | 117 +- .../apiserver/pkg/registry/generic/doc.go | 2 +- .../generic/registry/corrupt_obj_deleter.go | 10 +- .../pkg/registry/generic/registry/doc.go | 2 +- .../generic/registry/storage_factory.go | 27 +- .../pkg/registry/generic/registry/store.go | 1 - .../apiserver/pkg/registry/rest/delete.go | 17 +- .../k8s.io/apiserver/pkg/registry/rest/doc.go | 2 +- .../apiserver/pkg/registry/rest/meta.go | 5 +- .../apiserver/pkg/registry/rest/validate.go | 321 ++ .../k8s.io/apiserver/pkg/server/config.go | 50 +- .../apiserver/pkg/server/deleted_kinds.go | 189 +- e2e/vendor/k8s.io/apiserver/pkg/server/doc.go | 2 +- .../apiserver/pkg/server/filters/doc.go | 2 +- .../server/filters/priority-and-fairness.go | 12 +- .../apiserver/pkg/server/genericapiserver.go | 77 +- .../apiserver/pkg/server/healthz/doc.go | 2 +- .../apiserver/pkg/server/httplog/doc.go | 2 +- .../k8s.io/apiserver/pkg/server/mux/doc.go | 2 +- .../pkg/server/options/api_enablement.go | 8 + .../apiserver/pkg/server/options/doc.go | 2 +- .../pkg/server/options/server_run_options.go | 46 +- .../server/options/serving_with_loopback.go | 12 +- .../pkg/server/resourceconfig/doc.go | 2 +- .../pkg/server/resourceconfig/helpers.go | 91 +- .../k8s.io/apiserver/pkg/server/routes/doc.go | 2 +- .../apiserver/pkg/server/routes/version.go | 4 +- .../apiserver/pkg/server/secure_serving.go | 57 +- .../apiserver/pkg/server/storage/doc.go | 2 +- .../pkg/server/storage/resource_config.go | 63 +- .../storage/resource_encoding_config.go | 17 +- .../apiserver/pkg/storage/cacher/cacher.go | 353 +- .../apiserver/pkg/storage/cacher/delegator.go | 437 ++ .../pkg/storage/cacher/delegator/interface.go | 113 + .../pkg/storage/cacher/metrics/metrics.go | 9 + .../cacher/{ => progress}/watch_progress.go | 16 +- .../apiserver/pkg/storage/cacher/ready.go | 84 +- .../apiserver/pkg/storage/cacher/store.go | 12 +- .../pkg/storage/cacher/store_btree.go | 204 +- .../apiserver/pkg/storage/cacher/util.go | 10 + .../pkg/storage/cacher/watch_cache.go | 181 +- .../storage/cacher/watch_cache_interval.go | 15 +- .../k8s.io/apiserver/pkg/storage/doc.go | 2 +- .../apiserver/pkg/storage/errors/doc.go | 2 +- .../apiserver/pkg/storage/etcd3/store.go | 85 +- .../apiserver/pkg/storage/etcd3/watcher.go | 73 +- .../apiserver/pkg/storage/interfaces.go | 45 + .../pkg/storage/storagebackend/config.go | 4 + .../k8s.io/apiserver/pkg/storage/util.go | 43 - .../pkg/util/compatibility/registry.go | 53 + .../pkg/util/compatibility/version.go | 65 + .../pkg/util/flowcontrol/apf_controller.go | 2 +- .../flowcontrol/fairqueuing/queueset/doc.go | 2 +- .../request/list_work_estimator.go | 36 +- .../apiserver/pkg/util/flushwriter/doc.go | 2 +- .../pkg/util/peerproxy/metrics/metrics.go | 5 + .../apiserver/pkg/validation/metrics.go | 88 + .../plugin/pkg/audit/buffered/doc.go | 2 +- .../plugin/pkg/audit/truncate/doc.go | 2 +- .../k8s.io/cloud-provider/config/doc.go | 2 +- .../cloud-provider/config/v1alpha1/doc.go | 2 +- .../controllers/node/config/v1alpha1/doc.go | 2 +- .../controllers/service/config/doc.go | 2 +- .../service/config/v1alpha1/doc.go | 2 +- e2e/vendor/k8s.io/cloud-provider/doc.go | 2 +- .../component-base/cli/flag/tracker_flag.go | 82 + .../component-base/compatibility/OWNERS | 13 + .../registry.go | 96 +- .../component-base/compatibility/version.go | 239 + .../k8s.io/component-base/config/doc.go | 2 +- .../component-base/config/v1alpha1/doc.go | 2 +- .../featuregate/feature_gate.go | 41 +- .../k8s.io/component-base/logs/api/v1/doc.go | 2 +- .../logs/api/v1/kube_features.go | 36 +- .../component-base/logs/api/v1/options.go | 6 +- .../metrics/testutil/testutil.go | 10 + .../component-base/tracing/api/v1/doc.go | 2 +- .../k8s.io/component-base/version/base.go | 2 +- .../k8s.io/component-base/version/version.go | 159 +- .../component-base/zpages/flagz/flagreader.go | 2 +- .../component-base/zpages/flagz/flagz.go | 42 +- .../zpages/httputil/httputil.go | 54 + .../component-helpers/resource/helpers.go | 104 +- .../scheduling/corev1/doc.go | 2 +- .../k8s.io/controller-manager/config/doc.go | 2 +- .../controller-manager/config/v1/doc.go | 2 +- .../controller-manager/config/v1alpha1/doc.go | 2 +- .../controller-manager/config/v1beta1/doc.go | 2 +- .../k8s.io/kube-openapi/pkg/spec3/fuzz.go | 146 +- .../k8s.io/pod-security-admission/api/doc.go | 2 +- .../policy/check_restrictedVolumes.go | 2 + .../pod-security-admission/policy/doc.go | 2 +- e2e/vendor/modules.txt | 111 +- .../sigs.k8s.io/randfill/CONTRIBUTING.md | 43 + .../gofuzz => sigs.k8s.io/randfill}/LICENSE | 6 +- e2e/vendor/sigs.k8s.io/randfill/NOTICE | 24 + e2e/vendor/sigs.k8s.io/randfill/OWNERS | 8 + .../sigs.k8s.io/randfill/OWNERS_ALIASES | 14 + .../gofuzz => sigs.k8s.io/randfill}/README.md | 45 +- .../sigs.k8s.io/randfill/SECURITY_CONTACTS | 16 + .../randfill}/bytesource/bytesource.go | 0 .../sigs.k8s.io/randfill/code-of-conduct.md | 3 + e2e/vendor/sigs.k8s.io/randfill/randfill.go | 682 +++ 359 files changed, 11145 insertions(+), 18557 deletions(-) delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/.travis.yml delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/LICENSE delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/README.md delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/arrays.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/converter.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/error.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/numerics.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/patterns.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/types.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/utils.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/validator.go delete mode 100644 e2e/vendor/github.com/asaskevich/govalidator/wercker.yml delete mode 100644 e2e/vendor/github.com/google/gofuzz/.travis.yml delete mode 100644 e2e/vendor/github.com/google/gofuzz/CONTRIBUTING.md delete mode 100644 e2e/vendor/github.com/google/gofuzz/doc.go delete mode 100644 e2e/vendor/github.com/google/gofuzz/fuzz.go delete mode 100644 e2e/vendor/github.com/gorilla/websocket/tls_handshake.go delete mode 100644 e2e/vendor/github.com/gorilla/websocket/tls_handshake_116.go delete mode 100644 e2e/vendor/github.com/gorilla/websocket/x_net_proxy.go create mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/body_wrapper.go create mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go create mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go delete mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.24.0.go create mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go delete mode 100644 e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/README.md delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go delete mode 100644 e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/apis/asn1/oid.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go create mode 100644 e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/stream_reader.go create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/registry/rest/validate.go create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator.go create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator/interface.go rename e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/{ => progress}/watch_progress.go (86%) create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/registry.go create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/version.go create mode 100644 e2e/vendor/k8s.io/apiserver/pkg/validation/metrics.go create mode 100644 e2e/vendor/k8s.io/component-base/cli/flag/tracker_flag.go create mode 100644 e2e/vendor/k8s.io/component-base/compatibility/OWNERS rename e2e/vendor/k8s.io/component-base/{featuregate => compatibility}/registry.go (78%) create mode 100644 e2e/vendor/k8s.io/component-base/compatibility/version.go create mode 100644 e2e/vendor/k8s.io/component-base/zpages/httputil/httputil.go create mode 100644 e2e/vendor/sigs.k8s.io/randfill/CONTRIBUTING.md rename e2e/vendor/{github.com/google/gofuzz => sigs.k8s.io/randfill}/LICENSE (99%) create mode 100644 e2e/vendor/sigs.k8s.io/randfill/NOTICE create mode 100644 e2e/vendor/sigs.k8s.io/randfill/OWNERS create mode 100644 e2e/vendor/sigs.k8s.io/randfill/OWNERS_ALIASES rename e2e/vendor/{github.com/google/gofuzz => sigs.k8s.io/randfill}/README.md (53%) create mode 100644 e2e/vendor/sigs.k8s.io/randfill/SECURITY_CONTACTS rename e2e/vendor/{github.com/google/gofuzz => sigs.k8s.io/randfill}/bytesource/bytesource.go (100%) create mode 100644 e2e/vendor/sigs.k8s.io/randfill/code-of-conduct.md create mode 100644 e2e/vendor/sigs.k8s.io/randfill/randfill.go diff --git a/e2e/go.mod b/e2e/go.mod index f8948bd02..5531ab8ae 100644 --- a/e2e/go.mod +++ b/e2e/go.mod @@ -1,8 +1,7 @@ module github.com/ceph/ceph-csi/e2e go 1.23.1 - -toolchain go1.23.4 +toolchain go1.24.1 // my own dependencies replace ( @@ -16,12 +15,12 @@ require ( github.com/onsi/ginkgo/v2 v2.23.4 github.com/onsi/gomega v1.37.0 // when updating k8s.io modules, update the 'replace' section below too - k8s.io/api v0.32.3 - k8s.io/apimachinery v0.32.3 + k8s.io/api v0.33.0 + k8s.io/apimachinery v0.33.0 k8s.io/client-go v12.0.0+incompatible - k8s.io/cloud-provider v0.32.3 + k8s.io/cloud-provider v0.33.0 k8s.io/kubernetes v1.32.3 - k8s.io/pod-security-admission v0.32.3 + k8s.io/pod-security-admission v0.33.0 ) replace ( @@ -39,12 +38,11 @@ replace ( require github.com/ceph/ceph-csi v2.0.1+incompatible require ( - cel.dev/expr v0.19.1 // indirect + cel.dev/expr v0.20.0 // indirect github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/antlr4-go/antlr/v4 v4.13.0 // indirect - github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect @@ -75,15 +73,14 @@ require ( github.com/golang/protobuf v1.5.4 // indirect github.com/google/btree v1.1.3 // indirect github.com/google/cadvisor v0.51.0 // indirect - github.com/google/cel-go v0.22.0 // indirect + github.com/google/cel-go v0.23.2 // indirect github.com/google/gnostic-models v0.6.9 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/gofuzz v1.2.0 // indirect github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/gorilla/websocket v1.5.0 // indirect + github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -112,19 +109,19 @@ require ( github.com/spf13/pflag v1.0.5 // indirect github.com/stoewer/go-strcase v1.3.0 // indirect github.com/x448/float16 v0.8.4 // indirect - go.etcd.io/etcd/api/v3 v3.5.16 // indirect - go.etcd.io/etcd/client/pkg/v3 v3.5.16 // indirect - go.etcd.io/etcd/client/v3 v3.5.16 // indirect + go.etcd.io/etcd/api/v3 v3.5.21 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.5.21 // indirect + go.etcd.io/etcd/client/v3 v3.5.21 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 // indirect go.opentelemetry.io/otel v1.34.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.27.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 // indirect go.opentelemetry.io/otel/metric v1.34.0 // indirect go.opentelemetry.io/otel/sdk v1.34.0 // indirect go.opentelemetry.io/otel/trace v1.34.0 // indirect - go.opentelemetry.io/proto/otlp v1.3.1 // indirect + go.opentelemetry.io/proto/otlp v1.4.0 // indirect go.uber.org/automaxprocs v1.6.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect @@ -136,36 +133,37 @@ require ( golang.org/x/sys v0.32.0 // indirect golang.org/x/term v0.31.0 // indirect golang.org/x/text v0.24.0 // indirect - golang.org/x/time v0.8.0 // indirect + golang.org/x/time v0.9.0 // indirect golang.org/x/tools v0.31.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect - google.golang.org/grpc v1.71.1 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a // indirect + google.golang.org/grpc v1.72.0 // indirect google.golang.org/protobuf v1.36.6 // indirect gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.32.1 // indirect - k8s.io/apiserver v0.32.3 // indirect - k8s.io/component-base v0.32.3 // indirect - k8s.io/component-helpers v0.32.3 // indirect - k8s.io/controller-manager v0.32.3 // indirect + k8s.io/apiserver v0.33.0 // indirect + k8s.io/component-base v0.33.0 // indirect + k8s.io/component-helpers v0.33.0 // indirect + k8s.io/controller-manager v0.33.0 // indirect k8s.io/cri-api v0.32.2 // indirect k8s.io/cri-client v0.0.0 // indirect k8s.io/csi-translation-lib v0.32.2 // indirect k8s.io/dynamic-resource-allocation v0.0.0 // indirect k8s.io/klog/v2 v2.130.1 // indirect - k8s.io/kms v0.32.3 // indirect - k8s.io/kube-openapi v0.0.0-20241212222426-2c72e554b1e7 // indirect + k8s.io/kms v0.33.0 // indirect + k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect k8s.io/kube-scheduler v0.0.0 // indirect k8s.io/kubectl v0.0.0 // indirect k8s.io/kubelet v0.32.2 // indirect k8s.io/mount-utils v0.32.2 // indirect k8s.io/utils v0.0.0-20241210054802-24370beab758 // indirect - sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.0 // indirect + sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 // indirect sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect - sigs.k8s.io/structured-merge-diff/v4 v4.5.0 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/e2e/go.sum b/e2e/go.sum index b46ff9ee5..05b6b1a07 100644 --- a/e2e/go.sum +++ b/e2e/go.sum @@ -1,5 +1,5 @@ -cel.dev/expr v0.19.1 h1:NciYrtDRIR0lNCnH1LFJegdjspNx9fI59O7TWcua/W4= -cel.dev/expr v0.19.1/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= +cel.dev/expr v0.20.0 h1:OunBvVCfvpWlt4dN7zg3FM6TDkzOePe1+foGJ9AXeeI= +cel.dev/expr v0.20.0/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab h1:UKkYhof1njT1/xq4SEg5z+VpTgjmNeHwPGRQl7takDI= github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab/go.mod h1:3VYc5hodBMJ5+l/7J4xAyMeuM2PNuepvHlGs8yilUCA= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= @@ -10,8 +10,6 @@ github.com/antlr4-go/antlr/v4 v4.13.0 h1:lxCg3LAv+EUK6t1i0y1V6/SLeUi0eKEKdhQAlS8 github.com/antlr4-go/antlr/v4 v4.13.0/go.mod h1:pfChB/xh/Unjila75QW7+VU4TSnWnnk9UTnmpPaOR2g= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= -github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA= -github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= @@ -81,16 +79,16 @@ github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= -github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= +github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/cadvisor v0.51.0 h1:BspqSPdZoLKrnvuZNOvM/KiJ/A+RdixwagN20n+2H8k= github.com/google/cadvisor v0.51.0/go.mod h1:czGE/c/P/i0QFpVNKTFrIEzord9Y10YfpwuaSWXELc0= -github.com/google/cel-go v0.22.0 h1:b3FJZxpiv1vTMo2/5RDUqAHPxkT8mmMfJIrq1llbf7g= -github.com/google/cel-go v0.22.0/go.mod h1:BuznPXXfQDpXKWQ9sPW3TzlAJN5zzFe+i9tIs0yC4s8= +github.com/google/cel-go v0.23.2 h1:UdEe3CvQh3Nv+E/j9r1Y//WO0K0cSyD7/y0bzyLIMI4= +github.com/google/cel-go v0.23.2/go.mod h1:52Pb6QsDbC5kvgxvZhiL9QX1oZEkcUF/ZqaPx1J5Wwo= github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= @@ -103,16 +101,16 @@ github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 h1:TmHmbvxPmaegwhDubVz0lICL0J5Ka2vwTzhoePEXsGE= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0/go.mod h1:qztMSjm835F2bXf+5HKAPIS5qsmQDqZna/PgVt4rWtI= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4= @@ -220,32 +218,32 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0= go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I= -go.etcd.io/etcd/api/v3 v3.5.16 h1:WvmyJVbjWqK4R1E+B12RRHz3bRGy9XVfh++MgbN+6n0= -go.etcd.io/etcd/api/v3 v3.5.16/go.mod h1:1P4SlIP/VwkDmGo3OlOD7faPeP8KDIFhqvciH5EfN28= -go.etcd.io/etcd/client/pkg/v3 v3.5.16 h1:ZgY48uH6UvB+/7R9Yf4x574uCO3jIx0TRDyetSfId3Q= -go.etcd.io/etcd/client/pkg/v3 v3.5.16/go.mod h1:V8acl8pcEK0Y2g19YlOV9m9ssUe6MgiDSobSoaBAM0E= -go.etcd.io/etcd/client/v2 v2.305.16 h1:kQrn9o5czVNaukf2A2At43cE9ZtWauOtf9vRZuiKXow= -go.etcd.io/etcd/client/v2 v2.305.16/go.mod h1:h9YxWCzcdvZENbfzBTFCnoNumr2ax3F19sKMqHFmXHE= -go.etcd.io/etcd/client/v3 v3.5.16 h1:sSmVYOAHeC9doqi0gv7v86oY/BTld0SEFGaxsU9eRhE= -go.etcd.io/etcd/client/v3 v3.5.16/go.mod h1:X+rExSGkyqxvu276cr2OwPLBaeqFu1cIl4vmRjAD/50= -go.etcd.io/etcd/pkg/v3 v3.5.16 h1:cnavs5WSPWeK4TYwPYfmcr3Joz9BH+TZ6qoUtz6/+mc= -go.etcd.io/etcd/pkg/v3 v3.5.16/go.mod h1:+lutCZHG5MBBFI/U4eYT5yL7sJfnexsoM20Y0t2uNuY= -go.etcd.io/etcd/raft/v3 v3.5.16 h1:zBXA3ZUpYs1AwiLGPafYAKKl/CORn/uaxYDwlNwndAk= -go.etcd.io/etcd/raft/v3 v3.5.16/go.mod h1:P4UP14AxofMJ/54boWilabqqWoW9eLodl6I5GdGzazI= -go.etcd.io/etcd/server/v3 v3.5.16 h1:d0/SAdJ3vVsZvF8IFVb1k8zqMZ+heGcNfft71ul9GWE= -go.etcd.io/etcd/server/v3 v3.5.16/go.mod h1:ynhyZZpdDp1Gq49jkUg5mfkDWZwXnn3eIqCqtJnrD/s= +go.etcd.io/etcd/api/v3 v3.5.21 h1:A6O2/JDb3tvHhiIz3xf9nJ7REHvtEFJJ3veW3FbCnS8= +go.etcd.io/etcd/api/v3 v3.5.21/go.mod h1:c3aH5wcvXv/9dqIw2Y810LDXJfhSYdHQ0vxmP3CCHVY= +go.etcd.io/etcd/client/pkg/v3 v3.5.21 h1:lPBu71Y7osQmzlflM9OfeIV2JlmpBjqBNlLtcoBqUTc= +go.etcd.io/etcd/client/pkg/v3 v3.5.21/go.mod h1:BgqT/IXPjK9NkeSDjbzwsHySX3yIle2+ndz28nVsjUs= +go.etcd.io/etcd/client/v2 v2.305.21 h1:eLiFfexc2mE+pTLz9WwnoEsX5JTTpLCYVivKkmVXIRA= +go.etcd.io/etcd/client/v2 v2.305.21/go.mod h1:OKkn4hlYNf43hpjEM3Ke3aRdUkhSl8xjKjSf8eCq2J8= +go.etcd.io/etcd/client/v3 v3.5.21 h1:T6b1Ow6fNjOLOtM0xSoKNQt1ASPCLWrF9XMHcH9pEyY= +go.etcd.io/etcd/client/v3 v3.5.21/go.mod h1:mFYy67IOqmbRf/kRUvsHixzo3iG+1OF2W2+jVIQRAnU= +go.etcd.io/etcd/pkg/v3 v3.5.21 h1:jUItxeKyrDuVuWhdh0HtjUANwyuzcb7/FAeUfABmQsk= +go.etcd.io/etcd/pkg/v3 v3.5.21/go.mod h1:wpZx8Egv1g4y+N7JAsqi2zoUiBIUWznLjqJbylDjWgU= +go.etcd.io/etcd/raft/v3 v3.5.21 h1:dOmE0mT55dIUsX77TKBLq+RgyumsQuYeiRQnW/ylugk= +go.etcd.io/etcd/raft/v3 v3.5.21/go.mod h1:fmcuY5R2SNkklU4+fKVBQi2biVp5vafMrWUEj4TJ4Cs= +go.etcd.io/etcd/server/v3 v3.5.21 h1:9w0/k12majtgarGmlMVuhwXRI2ob3/d1Ik3X5TKo0yU= +go.etcd.io/etcd/server/v3 v3.5.21/go.mod h1:G1mOzdwuzKT1VRL7SqRchli/qcFrtLBTAQ4lV20sXXo= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0 h1:PS8wXpbyaDJQ2VDHHncMe9Vct0Zn1fEjpsjrLxGJoSc= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.58.0/go.mod h1:HDBUsEjOuRC0EzKZ1bSaRGZWUBAzo+MhAcUUORSr4D0= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 h1:4K4tsIXefpVJtvA/8srF4V4y0akAoPHkIslgAkjixJA= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0/go.mod h1:jjdQuTGVsXV4vSs+CJ2qYDeDPf9yIJV23qlIzBm73Vg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 h1:3Q/xZUyC1BBkualc9ROb4G8qkH90LXEIICcs5zv1OYY= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0/go.mod h1:s75jGIWA9OfCMzF0xr+ZgfrB5FEbbV7UuYo32ahUiFI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.27.0 h1:qFffATk0X+HD+f1Z8lswGiOQYKHRlzfmdJm0wEaVrFA= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.27.0/go.mod h1:MOiCmryaYtc+V0Ei+Tx9o5S1ZjA7kzLucuVuyzBZloQ= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 h1:5pojmb1U1AogINhN3SurB+zm/nIcusopeBNp42f45QM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0/go.mod h1:57gTHJSE5S1tqg+EKsLPlTWhpHMsWlVmer+LA926XiA= go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= @@ -254,8 +252,8 @@ go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= -go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= -go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg= +go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -298,8 +296,8 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= -golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= -golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -312,12 +310,12 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80 h1:KAeGQVN3M9nD0/bQXnr/ClcEMJ968gUXJQ9pwfSynuQ= google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80/go.mod h1:cc8bqMqtv9gMOr0zHg2Vzff5ULhhL2IXP4sbcn32Dro= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= -google.golang.org/grpc v1.71.1 h1:ffsFWr7ygTUscGPI0KKK6TLrGz0476KUvvsbqWK0rPI= -google.golang.org/grpc v1.71.1/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a h1:nwKuGPlUAt+aR+pcrkfFRrTU1BVrSmYyYMxYbUIVHr0= +google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a/go.mod h1:3kWAYMk1I75K4vykHtKt2ycnOgpA6974V7bREqbsenU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ= +google.golang.org/grpc v1.72.0 h1:S7UkcVa60b5AAQTaO6ZKamFp1zMZSU0fGDK2WZLbBnM= +google.golang.org/grpc v1.72.0/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -336,20 +334,20 @@ k8s.io/api v0.32.2 h1:bZrMLEkgizC24G9eViHGOPbW+aRo9duEISRIJKfdJuw= k8s.io/api v0.32.2/go.mod h1:hKlhk4x1sJyYnHENsrdCWw31FEmCijNGPJO5WzHiJ6Y= k8s.io/apiextensions-apiserver v0.32.2 h1:2YMk285jWMk2188V2AERy5yDwBYrjgWYggscghPCvV4= k8s.io/apiextensions-apiserver v0.32.2/go.mod h1:GPwf8sph7YlJT3H6aKUWtd0E+oyShk/YHWQHf/OOgCA= -k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= -k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= -k8s.io/apiserver v0.32.3 h1:kOw2KBuHOA+wetX1MkmrxgBr648ksz653j26ESuWNY8= -k8s.io/apiserver v0.32.3/go.mod h1:q1x9B8E/WzShF49wh3ADOh6muSfpmFL0I2t+TG0Zdgc= +k8s.io/apimachinery v0.33.0 h1:1a6kHrJxb2hs4t8EE5wuR/WxKDwGN1FKH3JvDtA0CIQ= +k8s.io/apimachinery v0.33.0/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/apiserver v0.33.0 h1:QqcM6c+qEEjkOODHppFXRiw/cE2zP85704YrQ9YaBbc= +k8s.io/apiserver v0.33.0/go.mod h1:EixYOit0YTxt8zrO2kBU7ixAtxFce9gKGq367nFmqI8= k8s.io/client-go v0.32.2 h1:4dYCD4Nz+9RApM2b/3BtVvBHw54QjMFUl1OLcJG5yOA= k8s.io/client-go v0.32.2/go.mod h1:fpZ4oJXclZ3r2nDOv+Ux3XcJutfrwjKTCHz2H3sww94= -k8s.io/cloud-provider v0.32.3 h1:WC7KhWrqXsU4b0E4tjS+nBectGiJbr1wuc1TpWXvtZM= -k8s.io/cloud-provider v0.32.3/go.mod h1:/fwBfgRPuh16n8vLHT+PPT+Bc4LAEaJYj38opO2wsYY= -k8s.io/component-base v0.32.3 h1:98WJvvMs3QZ2LYHBzvltFSeJjEx7t5+8s71P7M74u8k= -k8s.io/component-base v0.32.3/go.mod h1:LWi9cR+yPAv7cu2X9rZanTiFKB2kHA+JjmhkKjCZRpI= -k8s.io/component-helpers v0.32.3 h1:9veHpOGTPLluqU4hAu5IPOwkOIZiGAJUhHndfVc5FT4= -k8s.io/component-helpers v0.32.3/go.mod h1:utTBXk8lhkJewBKNuNf32Xl3KT/0VV19DmiXU/SV4Ao= -k8s.io/controller-manager v0.32.3 h1:jBxZnQ24k6IMeWLyxWZmpa3QVS7ww+osAIzaUY/jqyc= -k8s.io/controller-manager v0.32.3/go.mod h1:out1L3DZjE/p7JG0MoMMIaQGWIkt3c+pKaswqSHgKsI= +k8s.io/cloud-provider v0.33.0 h1:nVU2Q9QK7O50yaNx+pE61oDPqflsSsKygN43f5js9+I= +k8s.io/cloud-provider v0.33.0/go.mod h1:2reyEBbsimZJKHF325vxLBD5fcJGNeJHeLjJ+jGM8Qg= +k8s.io/component-base v0.33.0 h1:Ot4PyJI+0JAD9covDhwLp9UNkUja209OzsJ4FzScBNk= +k8s.io/component-base v0.33.0/go.mod h1:aXYZLbw3kihdkOPMDhWbjGCO6sg+luw554KP51t8qCU= +k8s.io/component-helpers v0.33.0 h1:0AdW0A0mIgljLgtG0hJDdJl52PPqTrtMgOgtm/9i/Ys= +k8s.io/component-helpers v0.33.0/go.mod h1:9SRiXfLldPw9lEEuSsapMtvT8j/h1JyFFapbtybwKvU= +k8s.io/controller-manager v0.33.0 h1:O9LnTjffOe62d66gMcKLuPXsBjY5sqETWEIzg+DVL8w= +k8s.io/controller-manager v0.33.0/go.mod h1:vQwAQnroav4+UyE2acW1Rj6CSsHPzr2/018kgRLYqlI= k8s.io/cri-api v0.32.2 h1:7DuaOHpOcXweZeBUbRdK0iCroxctGp73VwgrA0u7kho= k8s.io/cri-api v0.32.2/go.mod h1:DCzMuTh2padoinefWME0G678Mc3QFbLMF2vEweGzBAI= k8s.io/cri-client v0.32.2 h1:vjowJUyu14IbmifqCKJHE9rK/BPSfkXvltqN42W1Zuo= @@ -360,10 +358,10 @@ k8s.io/dynamic-resource-allocation v0.32.2 h1:6wP8/GGvhhvTJLrzwPSoMJDnspmosFj1CK k8s.io/dynamic-resource-allocation v0.32.2/go.mod h1:+3qnQfvikLHVZrdZ0/gYkRiV96weUR9j7+Ph3Ui/hYU= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kms v0.32.3 h1:HhHw5+pRCzEJp3oFFJ1q5W2N6gAI7YkUg4ay4Z0dgwM= -k8s.io/kms v0.32.3/go.mod h1:Bk2evz/Yvk0oVrvm4MvZbgq8BD34Ksxs2SRHn4/UiOM= -k8s.io/kube-openapi v0.0.0-20241212222426-2c72e554b1e7 h1:hcha5B1kVACrLujCKLbr8XWMxCxzQx42DY8QKYJrDLg= -k8s.io/kube-openapi v0.0.0-20241212222426-2c72e554b1e7/go.mod h1:GewRfANuJ70iYzvn+i4lezLDAFzvjxZYK1gn1lWcfas= +k8s.io/kms v0.33.0 h1:fhQSW/vyaWDhMp0vDuO/sLg2RlGZf4F77beSXcB4/eE= +k8s.io/kms v0.33.0/go.mod h1:C1I8mjFFBNzfUZXYt9FZVJ8MJl7ynFbGgZFbBzkBJ3E= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= k8s.io/kube-scheduler v0.32.2 h1:vBm6iIjWaD10OPmtkt/503LTKvrN8dWVceeBcpKj/ns= k8s.io/kube-scheduler v0.32.2/go.mod h1:dD5yuYpnsCfgZmzvncUNPdvXGJXA1hw3gXq7DH3+aCQ= k8s.io/kubectl v0.32.2 h1:TAkag6+XfSBgkqK9I7ZvwtF0WVtUAvK8ZqTt+5zi1Us= @@ -374,15 +372,18 @@ k8s.io/kubernetes v1.32.3 h1:2A58BlNME8NwsMawmnM6InYo3Jf35Nw5G79q46kXwoA= k8s.io/kubernetes v1.32.3/go.mod h1:GvhiBeolvSRzBpFlgM0z/Bbu3Oxs9w3P6XfEgYaMi8k= k8s.io/mount-utils v0.32.2 h1:aDwp+ucWiVnDr/LpRg88/dsXf/vm6gI1VZkYH3+3+Vw= k8s.io/mount-utils v0.32.2/go.mod h1:Kun5c2svjAPx0nnvJKYQWhfeNW+O0EpzHgRhDcYoSY0= -k8s.io/pod-security-admission v0.32.3 h1:scV0PQc3PdD6sXOMHukPZOCzGCGZeVN5z999gHBpkOc= -k8s.io/pod-security-admission v0.32.3/go.mod h1:K1saHV9cPicHSnQuavHxR1zohKhHMajbk8e0Z7pXAdc= +k8s.io/pod-security-admission v0.33.0 h1:di/iicB5plCq+iQeqgf2s1N5DOSzTDiOOv5OiAbuYWE= +k8s.io/pod-security-admission v0.33.0/go.mod h1:McuUMtSclLNxQdCkDTTWqKR79jnpHT/022GuanVU/Wg= k8s.io/utils v0.0.0-20241210054802-24370beab758 h1:sdbE21q2nlQtFh65saZY+rRM6x6aJJI8IUa1AmH/qa0= k8s.io/utils v0.0.0-20241210054802-24370beab758/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.0 h1:CPT0ExVicCzcpeN4baWEV2ko2Z/AsiZgEdwgcfwLgMo= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.0/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 h1:jpcvIRr3GLoUoEKRkHKSmGjxb6lWwrBlJsXc+eUYQHM= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 h1:gBQPwqORJ8d8/YNZWEjoZs7npUVDpVXUUOFfW6CgAqE= sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/structured-merge-diff/v4 v4.5.0 h1:nbCitCK2hfnhyiKo6uf2HxUPTCodY6Qaf85SbDIaMBk= -sigs.k8s.io/structured-merge-diff/v4 v4.5.0/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4= +sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/e2e/vendor/cel.dev/expr/README.md b/e2e/vendor/cel.dev/expr/README.md index 7930c0b75..42d67f87c 100644 --- a/e2e/vendor/cel.dev/expr/README.md +++ b/e2e/vendor/cel.dev/expr/README.md @@ -69,5 +69,3 @@ For more detail, see: * [Language Definition](doc/langdef.md) Released under the [Apache License](LICENSE). - -Disclaimer: This is not an official Google product. diff --git a/e2e/vendor/github.com/asaskevich/govalidator/.travis.yml b/e2e/vendor/github.com/asaskevich/govalidator/.travis.yml deleted file mode 100644 index e29f8eef5..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: - - 1.1 - - 1.2 - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - tip - -notifications: - email: - - bwatas@gmail.com diff --git a/e2e/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md b/e2e/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md deleted file mode 100644 index f0f7e3a8a..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md +++ /dev/null @@ -1,63 +0,0 @@ -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [ ] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Financial contributions - -We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/govalidator). -Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed. - - -## Credits - - -### Contributors - -Thank you to all the people who have already contributed to govalidator! - - - -### Backers - -Thank you to all our backers! [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/govalidator#sponsor)) - - - - - - - - - - - \ No newline at end of file diff --git a/e2e/vendor/github.com/asaskevich/govalidator/LICENSE b/e2e/vendor/github.com/asaskevich/govalidator/LICENSE deleted file mode 100644 index 2f9a31fad..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Alex Saskevich - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/e2e/vendor/github.com/asaskevich/govalidator/README.md b/e2e/vendor/github.com/asaskevich/govalidator/README.md deleted file mode 100644 index 40f9a8781..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/README.md +++ /dev/null @@ -1,507 +0,0 @@ -govalidator -=========== -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/asaskevich/govalidator?status.png)](https://godoc.org/github.com/asaskevich/govalidator) [![Coverage Status](https://img.shields.io/coveralls/asaskevich/govalidator.svg)](https://coveralls.io/r/asaskevich/govalidator?branch=master) [![wercker status](https://app.wercker.com/status/1ec990b09ea86c910d5f08b0e02c6043/s "wercker status")](https://app.wercker.com/project/bykey/1ec990b09ea86c910d5f08b0e02c6043) -[![Build Status](https://travis-ci.org/asaskevich/govalidator.svg?branch=master)](https://travis-ci.org/asaskevich/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/asaskevich/govalidator)](https://goreportcard.com/report/github.com/asaskevich/govalidator) [![GoSearch](http://go-search.org/badge?id=github.com%2Fasaskevich%2Fgovalidator)](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [![Backers on Open Collective](https://opencollective.com/govalidator/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/govalidator/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_shield) - -A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js). - -#### Installation -Make sure that Go is installed on your computer. -Type the following command in your terminal: - - go get github.com/asaskevich/govalidator - -or you can get specified release of the package with `gopkg.in`: - - go get gopkg.in/asaskevich/govalidator.v4 - -After it the package is ready to use. - - -#### Import package in your project -Add following line in your `*.go` file: -```go -import "github.com/asaskevich/govalidator" -``` -If you are unhappy to use long `govalidator`, you can do something like this: -```go -import ( - valid "github.com/asaskevich/govalidator" -) -``` - -#### Activate behavior to require all fields have a validation tag by default -`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function. - -`SetNilPtrAllowedByRequired` causes validation to pass when struct fields marked by `required` are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between `nil` and `zero value` state can use this. If disabled, both `nil` and `zero` values cause validation errors. - -```go -import "github.com/asaskevich/govalidator" - -func init() { - govalidator.SetFieldsRequiredByDefault(true) -} -``` - -Here's some code to explain it: -```go -// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -type exampleStruct struct { - Name string `` - Email string `valid:"email"` -} - -// this, however, will only fail when Email is empty or an invalid email address: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email"` -} - -// lastly, this will only fail when Email is an invalid email address but not when it's empty: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email,optional"` -} -``` - -#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123)) -##### Custom validator function signature -A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible. -```go -import "github.com/asaskevich/govalidator" - -// old signature -func(i interface{}) bool - -// new signature -func(i interface{}, o interface{}) bool -``` - -##### Adding a custom validator -This was changed to prevent data races when accessing custom validators. -```go -import "github.com/asaskevich/govalidator" - -// before -govalidator.CustomTypeTagMap["customByteArrayValidator"] = CustomTypeValidator(func(i interface{}, o interface{}) bool { - // ... -}) - -// after -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - // ... -})) -``` - -#### List of functions: -```go -func Abs(value float64) float64 -func BlackList(str, chars string) string -func ByteLength(str string, params ...string) bool -func CamelCaseToUnderscore(str string) string -func Contains(str, substring string) bool -func Count(array []interface{}, iterator ConditionIterator) int -func Each(array []interface{}, iterator Iterator) -func ErrorByField(e error, field string) string -func ErrorsByField(e error) map[string]string -func Filter(array []interface{}, iterator ConditionIterator) []interface{} -func Find(array []interface{}, iterator ConditionIterator) interface{} -func GetLine(s string, index int) (string, error) -func GetLines(s string) []string -func InRange(value, left, right float64) bool -func IsASCII(str string) bool -func IsAlpha(str string) bool -func IsAlphanumeric(str string) bool -func IsBase64(str string) bool -func IsByteLength(str string, min, max int) bool -func IsCIDR(str string) bool -func IsCreditCard(str string) bool -func IsDNSName(str string) bool -func IsDataURI(str string) bool -func IsDialString(str string) bool -func IsDivisibleBy(str, num string) bool -func IsEmail(str string) bool -func IsFilePath(str string) (bool, int) -func IsFloat(str string) bool -func IsFullWidth(str string) bool -func IsHalfWidth(str string) bool -func IsHexadecimal(str string) bool -func IsHexcolor(str string) bool -func IsHost(str string) bool -func IsIP(str string) bool -func IsIPv4(str string) bool -func IsIPv6(str string) bool -func IsISBN(str string, version int) bool -func IsISBN10(str string) bool -func IsISBN13(str string) bool -func IsISO3166Alpha2(str string) bool -func IsISO3166Alpha3(str string) bool -func IsISO693Alpha2(str string) bool -func IsISO693Alpha3b(str string) bool -func IsISO4217(str string) bool -func IsIn(str string, params ...string) bool -func IsInt(str string) bool -func IsJSON(str string) bool -func IsLatitude(str string) bool -func IsLongitude(str string) bool -func IsLowerCase(str string) bool -func IsMAC(str string) bool -func IsMongoID(str string) bool -func IsMultibyte(str string) bool -func IsNatural(value float64) bool -func IsNegative(value float64) bool -func IsNonNegative(value float64) bool -func IsNonPositive(value float64) bool -func IsNull(str string) bool -func IsNumeric(str string) bool -func IsPort(str string) bool -func IsPositive(value float64) bool -func IsPrintableASCII(str string) bool -func IsRFC3339(str string) bool -func IsRFC3339WithoutZone(str string) bool -func IsRGBcolor(str string) bool -func IsRequestURI(rawurl string) bool -func IsRequestURL(rawurl string) bool -func IsSSN(str string) bool -func IsSemver(str string) bool -func IsTime(str string, format string) bool -func IsURL(str string) bool -func IsUTFDigit(str string) bool -func IsUTFLetter(str string) bool -func IsUTFLetterNumeric(str string) bool -func IsUTFNumeric(str string) bool -func IsUUID(str string) bool -func IsUUIDv3(str string) bool -func IsUUIDv4(str string) bool -func IsUUIDv5(str string) bool -func IsUpperCase(str string) bool -func IsVariableWidth(str string) bool -func IsWhole(value float64) bool -func LeftTrim(str, chars string) string -func Map(array []interface{}, iterator ResultIterator) []interface{} -func Matches(str, pattern string) bool -func NormalizeEmail(str string) (string, error) -func PadBoth(str string, padStr string, padLen int) string -func PadLeft(str string, padStr string, padLen int) string -func PadRight(str string, padStr string, padLen int) string -func Range(str string, params ...string) bool -func RemoveTags(s string) string -func ReplacePattern(str, pattern, replace string) string -func Reverse(s string) string -func RightTrim(str, chars string) string -func RuneLength(str string, params ...string) bool -func SafeFileName(str string) string -func SetFieldsRequiredByDefault(value bool) -func Sign(value float64) float64 -func StringLength(str string, params ...string) bool -func StringMatches(s string, params ...string) bool -func StripLow(str string, keepNewLines bool) string -func ToBoolean(str string) (bool, error) -func ToFloat(str string) (float64, error) -func ToInt(str string) (int64, error) -func ToJSON(obj interface{}) (string, error) -func ToString(obj interface{}) string -func Trim(str, chars string) string -func Truncate(str string, length int, ending string) string -func UnderscoreToCamelCase(s string) string -func ValidateStruct(s interface{}) (bool, error) -func WhiteList(str, chars string) string -type ConditionIterator -type CustomTypeValidator -type Error -func (e Error) Error() string -type Errors -func (es Errors) Error() string -func (es Errors) Errors() []error -type ISO3166Entry -type Iterator -type ParamValidator -type ResultIterator -type UnsupportedTypeError -func (e *UnsupportedTypeError) Error() string -type Validator -``` - -#### Examples -###### IsURL -```go -println(govalidator.IsURL(`http://user@pass:domain.com/path/page`)) -``` -###### ToString -```go -type User struct { - FirstName string - LastName string -} - -str := govalidator.ToString(&User{"John", "Juan"}) -println(str) -``` -###### Each, Map, Filter, Count for slices -Each iterates over the slice/array and calls Iterator for every item -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.Iterator = func(value interface{}, index int) { - println(value.(int)) -} -govalidator.Each(data, fn) -``` -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} { - return value.(int) * 3 -} -_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} -``` -```go -data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -var fn govalidator.ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 -} -_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} -_ = govalidator.Count(data, fn) // result = 5 -``` -###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2) -If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this: -```go -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) -``` -For completely custom validators (interface-based), see below. - -Here is a list of available validators for struct fields (validator - used function): -```go -"email": IsEmail, -"url": IsURL, -"dialstring": IsDialString, -"requrl": IsRequestURL, -"requri": IsRequestURI, -"alpha": IsAlpha, -"utfletter": IsUTFLetter, -"alphanum": IsAlphanumeric, -"utfletternum": IsUTFLetterNumeric, -"numeric": IsNumeric, -"utfnumeric": IsUTFNumeric, -"utfdigit": IsUTFDigit, -"hexadecimal": IsHexadecimal, -"hexcolor": IsHexcolor, -"rgbcolor": IsRGBcolor, -"lowercase": IsLowerCase, -"uppercase": IsUpperCase, -"int": IsInt, -"float": IsFloat, -"null": IsNull, -"uuid": IsUUID, -"uuidv3": IsUUIDv3, -"uuidv4": IsUUIDv4, -"uuidv5": IsUUIDv5, -"creditcard": IsCreditCard, -"isbn10": IsISBN10, -"isbn13": IsISBN13, -"json": IsJSON, -"multibyte": IsMultibyte, -"ascii": IsASCII, -"printableascii": IsPrintableASCII, -"fullwidth": IsFullWidth, -"halfwidth": IsHalfWidth, -"variablewidth": IsVariableWidth, -"base64": IsBase64, -"datauri": IsDataURI, -"ip": IsIP, -"port": IsPort, -"ipv4": IsIPv4, -"ipv6": IsIPv6, -"dns": IsDNSName, -"host": IsHost, -"mac": IsMAC, -"latitude": IsLatitude, -"longitude": IsLongitude, -"ssn": IsSSN, -"semver": IsSemver, -"rfc3339": IsRFC3339, -"rfc3339WithoutZone": IsRFC3339WithoutZone, -"ISO3166Alpha2": IsISO3166Alpha2, -"ISO3166Alpha3": IsISO3166Alpha3, -``` -Validators with parameters - -```go -"range(min|max)": Range, -"length(min|max)": ByteLength, -"runelength(min|max)": RuneLength, -"stringlength(min|max)": StringLength, -"matches(pattern)": StringMatches, -"in(string1|string2|...|stringN)": IsIn, -"rsapub(keylength)" : IsRsaPub, -``` - -And here is small example of usage: -```go -type Post struct { - Title string `valid:"alphanum,required"` - Message string `valid:"duck,ascii"` - Message2 string `valid:"animal(dog)"` - AuthorIP string `valid:"ipv4"` - Date string `valid:"-"` -} -post := &Post{ - Title: "My Example Post", - Message: "duck", - Message2: "dog", - AuthorIP: "123.234.54.3", -} - -// Add your own struct validation tags -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) - -// Add your own struct validation tags with parameter -govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool { - species := params[0] - return str == species -}) -govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$") - -result, err := govalidator.ValidateStruct(post) -if err != nil { - println("error: " + err.Error()) -} -println(result) -``` -###### WhiteList -```go -// Remove all characters from string ignoring characters between "a" and "z" -println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") -``` - -###### Custom validation functions -Custom validation using your own domain specific validators is also available - here's an example of how to use it: -```go -import "github.com/asaskevich/govalidator" - -type CustomByteArray [6]byte // custom types are supported and can be validated - -type StructWithCustomByteArray struct { - ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence - Email string `valid:"email"` - CustomMinLength int `valid:"-"` -} - -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool { - switch v := context.(type) { // you can type switch on the context interface being validated - case StructWithCustomByteArray: - // you can check and validate against some other field in the context, - // return early or not validate against the context at all – your choice - case SomeOtherType: - // ... - default: - // expecting some other type? Throw/panic here or continue - } - - switch v := i.(type) { // type switch on the struct field being validated - case CustomByteArray: - for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes - if e != 0 { - return true - } - } - } - return false -})) -govalidator.CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool { - switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation - case StructWithCustomByteArray: - return len(v.ID) >= v.CustomMinLength - } - return false -})) -``` - -###### Custom error messages -Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it: -```go -type Ticket struct { - Id int64 `json:"id"` - FirstName string `json:"firstname" valid:"required~First name is blank"` -} -``` - -#### Notes -Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator). -Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator). - -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [ ] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Credits -### Contributors - -This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. - -#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors) -* [Daniel Lohse](https://github.com/annismckenzie) -* [Attila Oláh](https://github.com/attilaolah) -* [Daniel Korner](https://github.com/Dadie) -* [Steven Wilkin](https://github.com/stevenwilkin) -* [Deiwin Sarjas](https://github.com/deiwin) -* [Noah Shibley](https://github.com/slugmobile) -* [Nathan Davies](https://github.com/nathj07) -* [Matt Sanford](https://github.com/mzsanford) -* [Simon ccl1115](https://github.com/ccl1115) - - - - -### Backers - -Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)] - - - - - - - - - - - - - - - -## License -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_large) \ No newline at end of file diff --git a/e2e/vendor/github.com/asaskevich/govalidator/arrays.go b/e2e/vendor/github.com/asaskevich/govalidator/arrays.go deleted file mode 100644 index 5bace2654..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/arrays.go +++ /dev/null @@ -1,58 +0,0 @@ -package govalidator - -// Iterator is the function that accepts element of slice/array and its index -type Iterator func(interface{}, int) - -// ResultIterator is the function that accepts element of slice/array and its index and returns any result -type ResultIterator func(interface{}, int) interface{} - -// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean -type ConditionIterator func(interface{}, int) bool - -// Each iterates over the slice and apply Iterator to every item -func Each(array []interface{}, iterator Iterator) { - for index, data := range array { - iterator(data, index) - } -} - -// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result. -func Map(array []interface{}, iterator ResultIterator) []interface{} { - var result = make([]interface{}, len(array)) - for index, data := range array { - result[index] = iterator(data, index) - } - return result -} - -// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise. -func Find(array []interface{}, iterator ConditionIterator) interface{} { - for index, data := range array { - if iterator(data, index) { - return data - } - } - return nil -} - -// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice. -func Filter(array []interface{}, iterator ConditionIterator) []interface{} { - var result = make([]interface{}, 0) - for index, data := range array { - if iterator(data, index) { - result = append(result, data) - } - } - return result -} - -// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator. -func Count(array []interface{}, iterator ConditionIterator) int { - count := 0 - for index, data := range array { - if iterator(data, index) { - count = count + 1 - } - } - return count -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/converter.go b/e2e/vendor/github.com/asaskevich/govalidator/converter.go deleted file mode 100644 index cf1e5d569..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/converter.go +++ /dev/null @@ -1,64 +0,0 @@ -package govalidator - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" -) - -// ToString convert the input to a string. -func ToString(obj interface{}) string { - res := fmt.Sprintf("%v", obj) - return string(res) -} - -// ToJSON convert the input to a valid JSON string -func ToJSON(obj interface{}) (string, error) { - res, err := json.Marshal(obj) - if err != nil { - res = []byte("") - } - return string(res), err -} - -// ToFloat convert the input string to a float, or 0.0 if the input is not a float. -func ToFloat(str string) (float64, error) { - res, err := strconv.ParseFloat(str, 64) - if err != nil { - res = 0.0 - } - return res, err -} - -// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. -func ToInt(value interface{}) (res int64, err error) { - val := reflect.ValueOf(value) - - switch value.(type) { - case int, int8, int16, int32, int64: - res = val.Int() - case uint, uint8, uint16, uint32, uint64: - res = int64(val.Uint()) - case string: - if IsInt(val.String()) { - res, err = strconv.ParseInt(val.String(), 0, 64) - if err != nil { - res = 0 - } - } else { - err = fmt.Errorf("math: square root of negative number %g", value) - res = 0 - } - default: - err = fmt.Errorf("math: square root of negative number %g", value) - res = 0 - } - - return -} - -// ToBoolean convert the input string to a boolean. -func ToBoolean(str string) (bool, error) { - return strconv.ParseBool(str) -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/error.go b/e2e/vendor/github.com/asaskevich/govalidator/error.go deleted file mode 100644 index 655b750cb..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/error.go +++ /dev/null @@ -1,43 +0,0 @@ -package govalidator - -import "strings" - -// Errors is an array of multiple errors and conforms to the error interface. -type Errors []error - -// Errors returns itself. -func (es Errors) Errors() []error { - return es -} - -func (es Errors) Error() string { - var errs []string - for _, e := range es { - errs = append(errs, e.Error()) - } - return strings.Join(errs, ";") -} - -// Error encapsulates a name, an error and whether there's a custom error message or not. -type Error struct { - Name string - Err error - CustomErrorMessageExists bool - - // Validator indicates the name of the validator that failed - Validator string - Path []string -} - -func (e Error) Error() string { - if e.CustomErrorMessageExists { - return e.Err.Error() - } - - errName := e.Name - if len(e.Path) > 0 { - errName = strings.Join(append(e.Path, e.Name), ".") - } - - return errName + ": " + e.Err.Error() -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/numerics.go b/e2e/vendor/github.com/asaskevich/govalidator/numerics.go deleted file mode 100644 index 7e6c652e1..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/numerics.go +++ /dev/null @@ -1,97 +0,0 @@ -package govalidator - -import ( - "math" - "reflect" -) - -// Abs returns absolute value of number -func Abs(value float64) float64 { - return math.Abs(value) -} - -// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise -func Sign(value float64) float64 { - if value > 0 { - return 1 - } else if value < 0 { - return -1 - } else { - return 0 - } -} - -// IsNegative returns true if value < 0 -func IsNegative(value float64) bool { - return value < 0 -} - -// IsPositive returns true if value > 0 -func IsPositive(value float64) bool { - return value > 0 -} - -// IsNonNegative returns true if value >= 0 -func IsNonNegative(value float64) bool { - return value >= 0 -} - -// IsNonPositive returns true if value <= 0 -func IsNonPositive(value float64) bool { - return value <= 0 -} - -// InRange returns true if value lies between left and right border -func InRangeInt(value, left, right interface{}) bool { - value64, _ := ToInt(value) - left64, _ := ToInt(left) - right64, _ := ToInt(right) - if left64 > right64 { - left64, right64 = right64, left64 - } - return value64 >= left64 && value64 <= right64 -} - -// InRange returns true if value lies between left and right border -func InRangeFloat32(value, left, right float32) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRange returns true if value lies between left and right border -func InRangeFloat64(value, left, right float64) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRange returns true if value lies between left and right border, generic type to handle int, float32 or float64, all types must the same type -func InRange(value interface{}, left interface{}, right interface{}) bool { - - reflectValue := reflect.TypeOf(value).Kind() - reflectLeft := reflect.TypeOf(left).Kind() - reflectRight := reflect.TypeOf(right).Kind() - - if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { - return InRangeInt(value.(int), left.(int), right.(int)) - } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { - return InRangeFloat32(value.(float32), left.(float32), right.(float32)) - } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { - return InRangeFloat64(value.(float64), left.(float64), right.(float64)) - } else { - return false - } -} - -// IsWhole returns true if value is whole number -func IsWhole(value float64) bool { - return math.Remainder(value, 1) == 0 -} - -// IsNatural returns true if value is natural number (positive and whole) -func IsNatural(value float64) bool { - return IsWhole(value) && IsPositive(value) -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/patterns.go b/e2e/vendor/github.com/asaskevich/govalidator/patterns.go deleted file mode 100644 index 61a05d438..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/patterns.go +++ /dev/null @@ -1,101 +0,0 @@ -package govalidator - -import "regexp" - -// Basic regular expressions for validating strings -const ( - Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$" - ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$" - ISBN13 string = "^(?:[0-9]{13})$" - UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" - UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" - Alpha string = "^[a-zA-Z]+$" - Alphanumeric string = "^[a-zA-Z0-9]+$" - Numeric string = "^[0-9]+$" - Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$" - Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" - Hexadecimal string = "^[0-9a-fA-F]+$" - Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" - RGBcolor string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" - ASCII string = "^[\x00-\x7F]+$" - Multibyte string = "[^\x00-\x7F]" - FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - PrintableASCII string = "^[\x20-\x7E]+$" - DataURI string = "^data:.+\\/(.+);base64$" - Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` - IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))` - URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)` - URLUsername string = `(\S+(:\S*)?@)` - URLPath string = `((\/|\?|#)[^\s]*)` - URLPort string = `(:(\d{1,5}))` - URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))` - URLSubdomain string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))` - URL string = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$` - SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` - WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` - UnixPath string = `^(/[^/\x00]*)+/?$` - Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" - tagName string = "valid" - hasLowerCase string = ".*[[:lower:]]" - hasUpperCase string = ".*[[:upper:]]" - hasWhitespace string = ".*[[:space:]]" - hasWhitespaceOnly string = "^[[:space:]]+$" -) - -// Used by IsFilePath func -const ( - // Unknown is unresolved OS type - Unknown = iota - // Win is Windows type - Win - // Unix is *nix OS types - Unix -) - -var ( - userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$") - hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$") - userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})") - rxEmail = regexp.MustCompile(Email) - rxCreditCard = regexp.MustCompile(CreditCard) - rxISBN10 = regexp.MustCompile(ISBN10) - rxISBN13 = regexp.MustCompile(ISBN13) - rxUUID3 = regexp.MustCompile(UUID3) - rxUUID4 = regexp.MustCompile(UUID4) - rxUUID5 = regexp.MustCompile(UUID5) - rxUUID = regexp.MustCompile(UUID) - rxAlpha = regexp.MustCompile(Alpha) - rxAlphanumeric = regexp.MustCompile(Alphanumeric) - rxNumeric = regexp.MustCompile(Numeric) - rxInt = regexp.MustCompile(Int) - rxFloat = regexp.MustCompile(Float) - rxHexadecimal = regexp.MustCompile(Hexadecimal) - rxHexcolor = regexp.MustCompile(Hexcolor) - rxRGBcolor = regexp.MustCompile(RGBcolor) - rxASCII = regexp.MustCompile(ASCII) - rxPrintableASCII = regexp.MustCompile(PrintableASCII) - rxMultibyte = regexp.MustCompile(Multibyte) - rxFullWidth = regexp.MustCompile(FullWidth) - rxHalfWidth = regexp.MustCompile(HalfWidth) - rxBase64 = regexp.MustCompile(Base64) - rxDataURI = regexp.MustCompile(DataURI) - rxLatitude = regexp.MustCompile(Latitude) - rxLongitude = regexp.MustCompile(Longitude) - rxDNSName = regexp.MustCompile(DNSName) - rxURL = regexp.MustCompile(URL) - rxSSN = regexp.MustCompile(SSN) - rxWinPath = regexp.MustCompile(WinPath) - rxUnixPath = regexp.MustCompile(UnixPath) - rxSemver = regexp.MustCompile(Semver) - rxHasLowerCase = regexp.MustCompile(hasLowerCase) - rxHasUpperCase = regexp.MustCompile(hasUpperCase) - rxHasWhitespace = regexp.MustCompile(hasWhitespace) - rxHasWhitespaceOnly = regexp.MustCompile(hasWhitespaceOnly) -) diff --git a/e2e/vendor/github.com/asaskevich/govalidator/types.go b/e2e/vendor/github.com/asaskevich/govalidator/types.go deleted file mode 100644 index 4f7e9274a..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/types.go +++ /dev/null @@ -1,636 +0,0 @@ -package govalidator - -import ( - "reflect" - "regexp" - "sort" - "sync" -) - -// Validator is a wrapper for a validator function that returns bool and accepts string. -type Validator func(str string) bool - -// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. -// The second parameter should be the context (in the case of validating a struct: the whole object being validated). -type CustomTypeValidator func(i interface{}, o interface{}) bool - -// ParamValidator is a wrapper for validator functions that accepts additional parameters. -type ParamValidator func(str string, params ...string) bool -type tagOptionsMap map[string]tagOption - -func (t tagOptionsMap) orderedKeys() []string { - var keys []string - for k := range t { - keys = append(keys, k) - } - - sort.Slice(keys, func(a, b int) bool { - return t[keys[a]].order < t[keys[b]].order - }) - - return keys -} - -type tagOption struct { - name string - customErrorMessage string - order int -} - -// UnsupportedTypeError is a wrapper for reflect.Type -type UnsupportedTypeError struct { - Type reflect.Type -} - -// stringValues is a slice of reflect.Value holding *reflect.StringValue. -// It implements the methods to sort by string. -type stringValues []reflect.Value - -// ParamTagMap is a map of functions accept variants parameters -var ParamTagMap = map[string]ParamValidator{ - "length": ByteLength, - "range": Range, - "runelength": RuneLength, - "stringlength": StringLength, - "matches": StringMatches, - "in": isInRaw, - "rsapub": IsRsaPub, -} - -// ParamTagRegexMap maps param tags to their respective regexes. -var ParamTagRegexMap = map[string]*regexp.Regexp{ - "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), - "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), - "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), - "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), - "in": regexp.MustCompile(`^in\((.*)\)`), - "matches": regexp.MustCompile(`^matches\((.+)\)$`), - "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), -} - -type customTypeTagMap struct { - validators map[string]CustomTypeValidator - - sync.RWMutex -} - -func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) { - tm.RLock() - defer tm.RUnlock() - v, ok := tm.validators[name] - return v, ok -} - -func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) { - tm.Lock() - defer tm.Unlock() - tm.validators[name] = ctv -} - -// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. -// Use this to validate compound or custom types that need to be handled as a whole, e.g. -// `type UUID [16]byte` (this would be handled as an array of bytes). -var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)} - -// TagMap is a map of functions, that can be used as tags for ValidateStruct function. -var TagMap = map[string]Validator{ - "email": IsEmail, - "url": IsURL, - "dialstring": IsDialString, - "requrl": IsRequestURL, - "requri": IsRequestURI, - "alpha": IsAlpha, - "utfletter": IsUTFLetter, - "alphanum": IsAlphanumeric, - "utfletternum": IsUTFLetterNumeric, - "numeric": IsNumeric, - "utfnumeric": IsUTFNumeric, - "utfdigit": IsUTFDigit, - "hexadecimal": IsHexadecimal, - "hexcolor": IsHexcolor, - "rgbcolor": IsRGBcolor, - "lowercase": IsLowerCase, - "uppercase": IsUpperCase, - "int": IsInt, - "float": IsFloat, - "null": IsNull, - "uuid": IsUUID, - "uuidv3": IsUUIDv3, - "uuidv4": IsUUIDv4, - "uuidv5": IsUUIDv5, - "creditcard": IsCreditCard, - "isbn10": IsISBN10, - "isbn13": IsISBN13, - "json": IsJSON, - "multibyte": IsMultibyte, - "ascii": IsASCII, - "printableascii": IsPrintableASCII, - "fullwidth": IsFullWidth, - "halfwidth": IsHalfWidth, - "variablewidth": IsVariableWidth, - "base64": IsBase64, - "datauri": IsDataURI, - "ip": IsIP, - "port": IsPort, - "ipv4": IsIPv4, - "ipv6": IsIPv6, - "dns": IsDNSName, - "host": IsHost, - "mac": IsMAC, - "latitude": IsLatitude, - "longitude": IsLongitude, - "ssn": IsSSN, - "semver": IsSemver, - "rfc3339": IsRFC3339, - "rfc3339WithoutZone": IsRFC3339WithoutZone, - "ISO3166Alpha2": IsISO3166Alpha2, - "ISO3166Alpha3": IsISO3166Alpha3, - "ISO4217": IsISO4217, -} - -// ISO3166Entry stores country codes -type ISO3166Entry struct { - EnglishShortName string - FrenchShortName string - Alpha2Code string - Alpha3Code string - Numeric string -} - -//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes" -var ISO3166List = []ISO3166Entry{ - {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"}, - {"Albania", "Albanie (l')", "AL", "ALB", "008"}, - {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"}, - {"Algeria", "Algérie (l')", "DZ", "DZA", "012"}, - {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"}, - {"Andorra", "Andorre (l')", "AD", "AND", "020"}, - {"Angola", "Angola (l')", "AO", "AGO", "024"}, - {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"}, - {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"}, - {"Argentina", "Argentine (l')", "AR", "ARG", "032"}, - {"Australia", "Australie (l')", "AU", "AUS", "036"}, - {"Austria", "Autriche (l')", "AT", "AUT", "040"}, - {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"}, - {"Bahrain", "Bahreïn", "BH", "BHR", "048"}, - {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"}, - {"Armenia", "Arménie (l')", "AM", "ARM", "051"}, - {"Barbados", "Barbade (la)", "BB", "BRB", "052"}, - {"Belgium", "Belgique (la)", "BE", "BEL", "056"}, - {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"}, - {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"}, - {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"}, - {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"}, - {"Botswana", "Botswana (le)", "BW", "BWA", "072"}, - {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"}, - {"Brazil", "Brésil (le)", "BR", "BRA", "076"}, - {"Belize", "Belize (le)", "BZ", "BLZ", "084"}, - {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"}, - {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"}, - {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"}, - {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"}, - {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"}, - {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"}, - {"Burundi", "Burundi (le)", "BI", "BDI", "108"}, - {"Belarus", "Bélarus (le)", "BY", "BLR", "112"}, - {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"}, - {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"}, - {"Canada", "Canada (le)", "CA", "CAN", "124"}, - {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"}, - {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"}, - {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"}, - {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"}, - {"Chad", "Tchad (le)", "TD", "TCD", "148"}, - {"Chile", "Chili (le)", "CL", "CHL", "152"}, - {"China", "Chine (la)", "CN", "CHN", "156"}, - {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"}, - {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"}, - {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"}, - {"Colombia", "Colombie (la)", "CO", "COL", "170"}, - {"Comoros (the)", "Comores (les)", "KM", "COM", "174"}, - {"Mayotte", "Mayotte", "YT", "MYT", "175"}, - {"Congo (the)", "Congo (le)", "CG", "COG", "178"}, - {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"}, - {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"}, - {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"}, - {"Croatia", "Croatie (la)", "HR", "HRV", "191"}, - {"Cuba", "Cuba", "CU", "CUB", "192"}, - {"Cyprus", "Chypre", "CY", "CYP", "196"}, - {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"}, - {"Benin", "Bénin (le)", "BJ", "BEN", "204"}, - {"Denmark", "Danemark (le)", "DK", "DNK", "208"}, - {"Dominica", "Dominique (la)", "DM", "DMA", "212"}, - {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"}, - {"Ecuador", "Équateur (l')", "EC", "ECU", "218"}, - {"El Salvador", "El Salvador", "SV", "SLV", "222"}, - {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"}, - {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"}, - {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"}, - {"Estonia", "Estonie (l')", "EE", "EST", "233"}, - {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"}, - {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"}, - {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"}, - {"Fiji", "Fidji (les)", "FJ", "FJI", "242"}, - {"Finland", "Finlande (la)", "FI", "FIN", "246"}, - {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"}, - {"France", "France (la)", "FR", "FRA", "250"}, - {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"}, - {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"}, - {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"}, - {"Djibouti", "Djibouti", "DJ", "DJI", "262"}, - {"Gabon", "Gabon (le)", "GA", "GAB", "266"}, - {"Georgia", "Géorgie (la)", "GE", "GEO", "268"}, - {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"}, - {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"}, - {"Germany", "Allemagne (l')", "DE", "DEU", "276"}, - {"Ghana", "Ghana (le)", "GH", "GHA", "288"}, - {"Gibraltar", "Gibraltar", "GI", "GIB", "292"}, - {"Kiribati", "Kiribati", "KI", "KIR", "296"}, - {"Greece", "Grèce (la)", "GR", "GRC", "300"}, - {"Greenland", "Groenland (le)", "GL", "GRL", "304"}, - {"Grenada", "Grenade (la)", "GD", "GRD", "308"}, - {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"}, - {"Guam", "Guam", "GU", "GUM", "316"}, - {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"}, - {"Guinea", "Guinée (la)", "GN", "GIN", "324"}, - {"Guyana", "Guyana (le)", "GY", "GUY", "328"}, - {"Haiti", "Haïti", "HT", "HTI", "332"}, - {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"}, - {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"}, - {"Honduras", "Honduras (le)", "HN", "HND", "340"}, - {"Hong Kong", "Hong Kong", "HK", "HKG", "344"}, - {"Hungary", "Hongrie (la)", "HU", "HUN", "348"}, - {"Iceland", "Islande (l')", "IS", "ISL", "352"}, - {"India", "Inde (l')", "IN", "IND", "356"}, - {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"}, - {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"}, - {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"}, - {"Ireland", "Irlande (l')", "IE", "IRL", "372"}, - {"Israel", "Israël", "IL", "ISR", "376"}, - {"Italy", "Italie (l')", "IT", "ITA", "380"}, - {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"}, - {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"}, - {"Japan", "Japon (le)", "JP", "JPN", "392"}, - {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"}, - {"Jordan", "Jordanie (la)", "JO", "JOR", "400"}, - {"Kenya", "Kenya (le)", "KE", "KEN", "404"}, - {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"}, - {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"}, - {"Kuwait", "Koweït (le)", "KW", "KWT", "414"}, - {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"}, - {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"}, - {"Lebanon", "Liban (le)", "LB", "LBN", "422"}, - {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"}, - {"Latvia", "Lettonie (la)", "LV", "LVA", "428"}, - {"Liberia", "Libéria (le)", "LR", "LBR", "430"}, - {"Libya", "Libye (la)", "LY", "LBY", "434"}, - {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"}, - {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"}, - {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"}, - {"Macao", "Macao", "MO", "MAC", "446"}, - {"Madagascar", "Madagascar", "MG", "MDG", "450"}, - {"Malawi", "Malawi (le)", "MW", "MWI", "454"}, - {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"}, - {"Maldives", "Maldives (les)", "MV", "MDV", "462"}, - {"Mali", "Mali (le)", "ML", "MLI", "466"}, - {"Malta", "Malte", "MT", "MLT", "470"}, - {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"}, - {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"}, - {"Mauritius", "Maurice", "MU", "MUS", "480"}, - {"Mexico", "Mexique (le)", "MX", "MEX", "484"}, - {"Monaco", "Monaco", "MC", "MCO", "492"}, - {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"}, - {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"}, - {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"}, - {"Montserrat", "Montserrat", "MS", "MSR", "500"}, - {"Morocco", "Maroc (le)", "MA", "MAR", "504"}, - {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"}, - {"Oman", "Oman", "OM", "OMN", "512"}, - {"Namibia", "Namibie (la)", "NA", "NAM", "516"}, - {"Nauru", "Nauru", "NR", "NRU", "520"}, - {"Nepal", "Népal (le)", "NP", "NPL", "524"}, - {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"}, - {"Curaçao", "Curaçao", "CW", "CUW", "531"}, - {"Aruba", "Aruba", "AW", "ABW", "533"}, - {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"}, - {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"}, - {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"}, - {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"}, - {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"}, - {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"}, - {"Niger (the)", "Niger (le)", "NE", "NER", "562"}, - {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"}, - {"Niue", "Niue", "NU", "NIU", "570"}, - {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"}, - {"Norway", "Norvège (la)", "NO", "NOR", "578"}, - {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"}, - {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"}, - {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"}, - {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"}, - {"Palau", "Palaos (les)", "PW", "PLW", "585"}, - {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"}, - {"Panama", "Panama (le)", "PA", "PAN", "591"}, - {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"}, - {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"}, - {"Peru", "Pérou (le)", "PE", "PER", "604"}, - {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"}, - {"Pitcairn", "Pitcairn", "PN", "PCN", "612"}, - {"Poland", "Pologne (la)", "PL", "POL", "616"}, - {"Portugal", "Portugal (le)", "PT", "PRT", "620"}, - {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"}, - {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"}, - {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"}, - {"Qatar", "Qatar (le)", "QA", "QAT", "634"}, - {"Réunion", "Réunion (La)", "RE", "REU", "638"}, - {"Romania", "Roumanie (la)", "RO", "ROU", "642"}, - {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"}, - {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"}, - {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"}, - {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"}, - {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"}, - {"Anguilla", "Anguilla", "AI", "AIA", "660"}, - {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"}, - {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"}, - {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"}, - {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"}, - {"San Marino", "Saint-Marin", "SM", "SMR", "674"}, - {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"}, - {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"}, - {"Senegal", "Sénégal (le)", "SN", "SEN", "686"}, - {"Serbia", "Serbie (la)", "RS", "SRB", "688"}, - {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"}, - {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"}, - {"Singapore", "Singapour", "SG", "SGP", "702"}, - {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"}, - {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"}, - {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"}, - {"Somalia", "Somalie (la)", "SO", "SOM", "706"}, - {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"}, - {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"}, - {"Spain", "Espagne (l')", "ES", "ESP", "724"}, - {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"}, - {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"}, - {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"}, - {"Suriname", "Suriname (le)", "SR", "SUR", "740"}, - {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"}, - {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"}, - {"Sweden", "Suède (la)", "SE", "SWE", "752"}, - {"Switzerland", "Suisse (la)", "CH", "CHE", "756"}, - {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"}, - {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"}, - {"Thailand", "Thaïlande (la)", "TH", "THA", "764"}, - {"Togo", "Togo (le)", "TG", "TGO", "768"}, - {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"}, - {"Tonga", "Tonga (les)", "TO", "TON", "776"}, - {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"}, - {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"}, - {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"}, - {"Turkey", "Turquie (la)", "TR", "TUR", "792"}, - {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"}, - {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"}, - {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"}, - {"Uganda", "Ouganda (l')", "UG", "UGA", "800"}, - {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"}, - {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"}, - {"Egypt", "Égypte (l')", "EG", "EGY", "818"}, - {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"}, - {"Guernsey", "Guernesey", "GG", "GGY", "831"}, - {"Jersey", "Jersey", "JE", "JEY", "832"}, - {"Isle of Man", "Île de Man", "IM", "IMN", "833"}, - {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"}, - {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"}, - {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"}, - {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"}, - {"Uruguay", "Uruguay (l')", "UY", "URY", "858"}, - {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"}, - {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"}, - {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"}, - {"Samoa", "Samoa (le)", "WS", "WSM", "882"}, - {"Yemen", "Yémen (le)", "YE", "YEM", "887"}, - {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"}, -} - -// ISO4217List is the list of ISO currency codes -var ISO4217List = []string{ - "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", - "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", - "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", - "DJF", "DKK", "DOP", "DZD", - "EGP", "ERN", "ETB", "EUR", - "FJD", "FKP", - "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", - "HKD", "HNL", "HRK", "HTG", "HUF", - "IDR", "ILS", "INR", "IQD", "IRR", "ISK", - "JMD", "JOD", "JPY", - "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", - "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", - "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", - "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", - "OMR", - "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", - "QAR", - "RON", "RSD", "RUB", "RWF", - "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "SVC", "SYP", "SZL", - "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", - "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UZS", - "VEF", "VND", "VUV", - "WST", - "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", - "YER", - "ZAR", "ZMW", "ZWL", -} - -// ISO693Entry stores ISO language codes -type ISO693Entry struct { - Alpha3bCode string - Alpha2Code string - English string -} - -//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json -var ISO693List = []ISO693Entry{ - {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"}, - {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"}, - {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"}, - {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"}, - {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"}, - {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"}, - {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"}, - {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"}, - {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"}, - {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"}, - {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"}, - {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"}, - {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"}, - {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"}, - {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"}, - {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"}, - {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"}, - {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"}, - {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"}, - {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"}, - {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"}, - {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"}, - {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"}, - {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"}, - {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"}, - {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"}, - {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"}, - {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"}, - {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"}, - {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"}, - {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"}, - {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"}, - {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"}, - {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"}, - {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"}, - {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"}, - {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"}, - {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"}, - {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"}, - {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"}, - {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"}, - {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"}, - {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"}, - {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"}, - {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"}, - {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"}, - {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"}, - {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"}, - {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"}, - {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"}, - {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"}, - {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"}, - {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"}, - {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"}, - {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"}, - {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"}, - {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"}, - {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"}, - {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"}, - {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"}, - {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"}, - {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"}, - {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"}, - {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"}, - {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"}, - {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"}, - {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"}, - {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"}, - {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"}, - {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"}, - {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"}, - {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"}, - {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"}, - {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"}, - {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"}, - {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"}, - {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"}, - {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"}, - {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"}, - {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"}, - {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"}, - {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"}, - {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"}, - {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"}, - {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"}, - {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"}, - {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"}, - {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"}, - {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"}, - {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"}, - {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"}, - {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"}, - {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"}, - {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"}, - {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"}, - {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"}, - {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"}, - {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"}, - {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"}, - {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"}, - {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"}, - {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"}, - {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"}, - {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"}, - {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"}, - {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"}, - {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"}, - {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"}, - {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"}, - {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"}, - {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"}, - {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"}, - {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"}, - {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"}, - {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"}, - {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"}, - {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"}, - {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"}, - {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"}, - {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"}, - {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"}, - {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"}, - {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"}, - {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"}, - {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"}, - {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"}, - {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"}, - {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"}, - {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"}, - {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"}, - {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"}, - {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"}, - {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"}, - {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"}, - {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"}, - {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"}, - {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"}, - {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"}, - {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"}, - {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"}, - {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"}, - {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"}, - {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"}, - {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"}, - {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"}, - {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"}, - {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"}, - {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"}, - {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"}, - {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"}, - {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"}, - {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"}, - {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"}, - {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"}, - {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"}, - {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"}, - {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"}, - {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"}, - {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"}, - {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"}, - {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"}, - {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"}, - {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"}, - {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"}, - {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"}, - {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"}, - {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"}, - {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"}, - {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"}, - {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"}, - {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"}, - {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"}, - {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"}, - {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"}, - {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"}, - {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"}, - {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"}, - {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"}, - {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"}, - {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"}, - {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"}, - {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"}, - {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"}, - {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"}, -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/utils.go b/e2e/vendor/github.com/asaskevich/govalidator/utils.go deleted file mode 100644 index a0b706a74..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/utils.go +++ /dev/null @@ -1,270 +0,0 @@ -package govalidator - -import ( - "errors" - "fmt" - "html" - "math" - "path" - "regexp" - "strings" - "unicode" - "unicode/utf8" -) - -// Contains check if the string contains the substring. -func Contains(str, substring string) bool { - return strings.Contains(str, substring) -} - -// Matches check if string matches the pattern (pattern is regular expression) -// In case of error return false -func Matches(str, pattern string) bool { - match, _ := regexp.MatchString(pattern, str) - return match -} - -// LeftTrim trim characters from the left-side of the input. -// If second argument is empty, it's will be remove leading spaces. -func LeftTrim(str, chars string) string { - if chars == "" { - return strings.TrimLeftFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("^[" + chars + "]+") - return r.ReplaceAllString(str, "") -} - -// RightTrim trim characters from the right-side of the input. -// If second argument is empty, it's will be remove spaces. -func RightTrim(str, chars string) string { - if chars == "" { - return strings.TrimRightFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("[" + chars + "]+$") - return r.ReplaceAllString(str, "") -} - -// Trim trim characters from both sides of the input. -// If second argument is empty, it's will be remove spaces. -func Trim(str, chars string) string { - return LeftTrim(RightTrim(str, chars), chars) -} - -// WhiteList remove characters that do not appear in the whitelist. -func WhiteList(str, chars string) string { - pattern := "[^" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// BlackList remove characters that appear in the blacklist. -func BlackList(str, chars string) string { - pattern := "[" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// StripLow remove characters with a numerical value < 32 and 127, mostly control characters. -// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). -func StripLow(str string, keepNewLines bool) string { - chars := "" - if keepNewLines { - chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F" - } else { - chars = "\x00-\x1F\x7F" - } - return BlackList(str, chars) -} - -// ReplacePattern replace regular expression pattern in string -func ReplacePattern(str, pattern, replace string) string { - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, replace) -} - -// Escape replace <, >, & and " with HTML entities. -var Escape = html.EscapeString - -func addSegment(inrune, segment []rune) []rune { - if len(segment) == 0 { - return inrune - } - if len(inrune) != 0 { - inrune = append(inrune, '_') - } - inrune = append(inrune, segment...) - return inrune -} - -// UnderscoreToCamelCase converts from underscore separated form to camel case form. -// Ex.: my_func => MyFunc -func UnderscoreToCamelCase(s string) string { - return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1) -} - -// CamelCaseToUnderscore converts from camel case form to underscore separated form. -// Ex.: MyFunc => my_func -func CamelCaseToUnderscore(str string) string { - var output []rune - var segment []rune - for _, r := range str { - - // not treat number as separate segment - if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) { - output = addSegment(output, segment) - segment = nil - } - segment = append(segment, unicode.ToLower(r)) - } - output = addSegment(output, segment) - return string(output) -} - -// Reverse return reversed string -func Reverse(s string) string { - r := []rune(s) - for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r) -} - -// GetLines split string by "\n" and return array of lines -func GetLines(s string) []string { - return strings.Split(s, "\n") -} - -// GetLine return specified line of multiline string -func GetLine(s string, index int) (string, error) { - lines := GetLines(s) - if index < 0 || index >= len(lines) { - return "", errors.New("line index out of bounds") - } - return lines[index], nil -} - -// RemoveTags remove all tags from HTML string -func RemoveTags(s string) string { - return ReplacePattern(s, "<[^>]*>", "") -} - -// SafeFileName return safe string that can be used in file names -func SafeFileName(str string) string { - name := strings.ToLower(str) - name = path.Clean(path.Base(name)) - name = strings.Trim(name, " ") - separators, err := regexp.Compile(`[ &_=+:]`) - if err == nil { - name = separators.ReplaceAllString(name, "-") - } - legal, err := regexp.Compile(`[^[:alnum:]-.]`) - if err == nil { - name = legal.ReplaceAllString(name, "") - } - for strings.Contains(name, "--") { - name = strings.Replace(name, "--", "-", -1) - } - return name -} - -// NormalizeEmail canonicalize an email address. -// The local part of the email address is lowercased for all domains; the hostname is always lowercased and -// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). -// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and -// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are -// normalized to @gmail.com. -func NormalizeEmail(str string) (string, error) { - if !IsEmail(str) { - return "", fmt.Errorf("%s is not an email", str) - } - parts := strings.Split(str, "@") - parts[0] = strings.ToLower(parts[0]) - parts[1] = strings.ToLower(parts[1]) - if parts[1] == "gmail.com" || parts[1] == "googlemail.com" { - parts[1] = "gmail.com" - parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0] - } - return strings.Join(parts, "@"), nil -} - -// Truncate a string to the closest length without breaking words. -func Truncate(str string, length int, ending string) string { - var aftstr, befstr string - if len(str) > length { - words := strings.Fields(str) - before, present := 0, 0 - for i := range words { - befstr = aftstr - before = present - aftstr = aftstr + words[i] + " " - present = len(aftstr) - if present > length && i != 0 { - if (length - before) < (present - length) { - return Trim(befstr, " /\\.,\"'#!?&@+-") + ending - } - return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending - } - } - } - - return str -} - -// PadLeft pad left side of string if size of string is less then indicated pad length -func PadLeft(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, false) -} - -// PadRight pad right side of string if size of string is less then indicated pad length -func PadRight(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, false, true) -} - -// PadBoth pad sides of string if size of string is less then indicated pad length -func PadBoth(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, true) -} - -// PadString either left, right or both sides, not the padding string can be unicode and more then one -// character -func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { - - // When padded length is less then the current string size - if padLen < utf8.RuneCountInString(str) { - return str - } - - padLen -= utf8.RuneCountInString(str) - - targetLen := padLen - - targetLenLeft := targetLen - targetLenRight := targetLen - if padLeft && padRight { - targetLenLeft = padLen / 2 - targetLenRight = padLen - targetLenLeft - } - - strToRepeatLen := utf8.RuneCountInString(padStr) - - repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) - repeatedString := strings.Repeat(padStr, repeatTimes) - - leftSide := "" - if padLeft { - leftSide = repeatedString[0:targetLenLeft] - } - - rightSide := "" - if padRight { - rightSide = repeatedString[0:targetLenRight] - } - - return leftSide + str + rightSide -} - -// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object -func TruncatingErrorf(str string, args ...interface{}) error { - n := strings.Count(str, "%s") - return fmt.Errorf(str, args[:n]...) -} diff --git a/e2e/vendor/github.com/asaskevich/govalidator/validator.go b/e2e/vendor/github.com/asaskevich/govalidator/validator.go deleted file mode 100644 index b18bbcb4c..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/validator.go +++ /dev/null @@ -1,1278 +0,0 @@ -// Package govalidator is package of validators and sanitizers for strings, structs and collections. -package govalidator - -import ( - "bytes" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "io/ioutil" - "net" - "net/url" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -var ( - fieldsRequiredByDefault bool - nilPtrAllowedByRequired = false - notNumberRegexp = regexp.MustCompile("[^0-9]+") - whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) - paramsRegexp = regexp.MustCompile(`\(.*\)$`) -) - -const maxURLRuneCount = 2083 -const minURLRuneCount = 3 -const RF3339WithoutZone = "2006-01-02T15:04:05" - -// SetFieldsRequiredByDefault causes validation to fail when struct fields -// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). -// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -// type exampleStruct struct { -// Name string `` -// Email string `valid:"email"` -// This, however, will only fail when Email is empty or an invalid email address: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email"` -// Lastly, this will only fail when Email is an invalid email address but not when it's empty: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email,optional"` -func SetFieldsRequiredByDefault(value bool) { - fieldsRequiredByDefault = value -} - -// SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. -// The validation will still reject ptr fields in their zero value state. Example with this enabled: -// type exampleStruct struct { -// Name *string `valid:"required"` -// With `Name` set to "", this will be considered invalid input and will cause a validation error. -// With `Name` set to nil, this will be considered valid by validation. -// By default this is disabled. -func SetNilPtrAllowedByRequired(value bool) { - nilPtrAllowedByRequired = value -} - -// IsEmail check if the string is an email. -func IsEmail(str string) bool { - // TODO uppercase letters are not supported - return rxEmail.MatchString(str) -} - -// IsExistingEmail check if the string is an email of existing domain -func IsExistingEmail(email string) bool { - - if len(email) < 6 || len(email) > 254 { - return false - } - at := strings.LastIndex(email, "@") - if at <= 0 || at > len(email)-3 { - return false - } - user := email[:at] - host := email[at+1:] - if len(user) > 64 { - return false - } - if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { - return false - } - switch host { - case "localhost", "example.com": - return true - } - if _, err := net.LookupMX(host); err != nil { - if _, err := net.LookupIP(host); err != nil { - return false - } - } - - return true -} - -// IsURL check if the string is an URL. -func IsURL(str string) bool { - if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { - return false - } - strTemp := str - if strings.Contains(str, ":") && !strings.Contains(str, "://") { - // support no indicated urlscheme but with colon for port number - // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString - strTemp = "http://" + str - } - u, err := url.Parse(strTemp) - if err != nil { - return false - } - if strings.HasPrefix(u.Host, ".") { - return false - } - if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { - return false - } - return rxURL.MatchString(str) -} - -// IsRequestURL check if the string rawurl, assuming -// it was received in an HTTP request, is a valid -// URL confirm to RFC 3986 -func IsRequestURL(rawurl string) bool { - url, err := url.ParseRequestURI(rawurl) - if err != nil { - return false //Couldn't even parse the rawurl - } - if len(url.Scheme) == 0 { - return false //No Scheme found - } - return true -} - -// IsRequestURI check if the string rawurl, assuming -// it was received in an HTTP request, is an -// absolute URI or an absolute path. -func IsRequestURI(rawurl string) bool { - _, err := url.ParseRequestURI(rawurl) - return err == nil -} - -// IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid. -func IsAlpha(str string) bool { - if IsNull(str) { - return true - } - return rxAlpha.MatchString(str) -} - -//IsUTFLetter check if the string contains only unicode letter characters. -//Similar to IsAlpha but for all languages. Empty string is valid. -func IsUTFLetter(str string) bool { - if IsNull(str) { - return true - } - - for _, c := range str { - if !unicode.IsLetter(c) { - return false - } - } - return true - -} - -// IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid. -func IsAlphanumeric(str string) bool { - if IsNull(str) { - return true - } - return rxAlphanumeric.MatchString(str) -} - -// IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid. -func IsUTFLetterNumeric(str string) bool { - if IsNull(str) { - return true - } - for _, c := range str { - if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok - return false - } - } - return true - -} - -// IsNumeric check if the string contains only numbers. Empty string is valid. -func IsNumeric(str string) bool { - if IsNull(str) { - return true - } - return rxNumeric.MatchString(str) -} - -// IsUTFNumeric check if the string contains only unicode numbers of any kind. -// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. -func IsUTFNumeric(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if !unicode.IsNumber(c) { //numbers && minus sign are ok - return false - } - } - return true - -} - -// IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid. -func IsUTFDigit(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if !unicode.IsDigit(c) { //digits && minus sign are ok - return false - } - } - return true - -} - -// IsHexadecimal check if the string is a hexadecimal number. -func IsHexadecimal(str string) bool { - return rxHexadecimal.MatchString(str) -} - -// IsHexcolor check if the string is a hexadecimal color. -func IsHexcolor(str string) bool { - return rxHexcolor.MatchString(str) -} - -// IsRGBcolor check if the string is a valid RGB color in form rgb(RRR, GGG, BBB). -func IsRGBcolor(str string) bool { - return rxRGBcolor.MatchString(str) -} - -// IsLowerCase check if the string is lowercase. Empty string is valid. -func IsLowerCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToLower(str) -} - -// IsUpperCase check if the string is uppercase. Empty string is valid. -func IsUpperCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToUpper(str) -} - -// HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid. -func HasLowerCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasLowerCase.MatchString(str) -} - -// HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid. -func HasUpperCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasUpperCase.MatchString(str) -} - -// IsInt check if the string is an integer. Empty string is valid. -func IsInt(str string) bool { - if IsNull(str) { - return true - } - return rxInt.MatchString(str) -} - -// IsFloat check if the string is a float. -func IsFloat(str string) bool { - return str != "" && rxFloat.MatchString(str) -} - -// IsDivisibleBy check if the string is a number that's divisible by another. -// If second argument is not valid integer or zero, it's return false. -// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). -func IsDivisibleBy(str, num string) bool { - f, _ := ToFloat(str) - p := int64(f) - q, _ := ToInt(num) - if q == 0 { - return false - } - return (p == 0) || (p%q == 0) -} - -// IsNull check if the string is null. -func IsNull(str string) bool { - return len(str) == 0 -} - -// HasWhitespaceOnly checks the string only contains whitespace -func HasWhitespaceOnly(str string) bool { - return len(str) > 0 && rxHasWhitespaceOnly.MatchString(str) -} - -// HasWhitespace checks if the string contains any whitespace -func HasWhitespace(str string) bool { - return len(str) > 0 && rxHasWhitespace.MatchString(str) -} - -// IsByteLength check if the string's length (in bytes) falls in a range. -func IsByteLength(str string, min, max int) bool { - return len(str) >= min && len(str) <= max -} - -// IsUUIDv3 check if the string is a UUID version 3. -func IsUUIDv3(str string) bool { - return rxUUID3.MatchString(str) -} - -// IsUUIDv4 check if the string is a UUID version 4. -func IsUUIDv4(str string) bool { - return rxUUID4.MatchString(str) -} - -// IsUUIDv5 check if the string is a UUID version 5. -func IsUUIDv5(str string) bool { - return rxUUID5.MatchString(str) -} - -// IsUUID check if the string is a UUID (version 3, 4 or 5). -func IsUUID(str string) bool { - return rxUUID.MatchString(str) -} - -// IsCreditCard check if the string is a credit card. -func IsCreditCard(str string) bool { - sanitized := notNumberRegexp.ReplaceAllString(str, "") - if !rxCreditCard.MatchString(sanitized) { - return false - } - var sum int64 - var digit string - var tmpNum int64 - var shouldDouble bool - for i := len(sanitized) - 1; i >= 0; i-- { - digit = sanitized[i:(i + 1)] - tmpNum, _ = ToInt(digit) - if shouldDouble { - tmpNum *= 2 - if tmpNum >= 10 { - sum += ((tmpNum % 10) + 1) - } else { - sum += tmpNum - } - } else { - sum += tmpNum - } - shouldDouble = !shouldDouble - } - - return sum%10 == 0 -} - -// IsISBN10 check if the string is an ISBN version 10. -func IsISBN10(str string) bool { - return IsISBN(str, 10) -} - -// IsISBN13 check if the string is an ISBN version 13. -func IsISBN13(str string) bool { - return IsISBN(str, 13) -} - -// IsISBN check if the string is an ISBN (version 10 or 13). -// If version value is not equal to 10 or 13, it will be check both variants. -func IsISBN(str string, version int) bool { - sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") - var checksum int32 - var i int32 - if version == 10 { - if !rxISBN10.MatchString(sanitized) { - return false - } - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(sanitized[i]-'0') - } - if sanitized[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(sanitized[9]-'0') - } - if checksum%11 == 0 { - return true - } - return false - } else if version == 13 { - if !rxISBN13.MatchString(sanitized) { - return false - } - factor := []int32{1, 3} - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(sanitized[i]-'0') - } - return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 - } - return IsISBN(str, 10) || IsISBN(str, 13) -} - -// IsJSON check if the string is valid JSON (note: uses json.Unmarshal). -func IsJSON(str string) bool { - var js json.RawMessage - return json.Unmarshal([]byte(str), &js) == nil -} - -// IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid. -func IsMultibyte(str string) bool { - if IsNull(str) { - return true - } - return rxMultibyte.MatchString(str) -} - -// IsASCII check if the string contains ASCII chars only. Empty string is valid. -func IsASCII(str string) bool { - if IsNull(str) { - return true - } - return rxASCII.MatchString(str) -} - -// IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid. -func IsPrintableASCII(str string) bool { - if IsNull(str) { - return true - } - return rxPrintableASCII.MatchString(str) -} - -// IsFullWidth check if the string contains any full-width chars. Empty string is valid. -func IsFullWidth(str string) bool { - if IsNull(str) { - return true - } - return rxFullWidth.MatchString(str) -} - -// IsHalfWidth check if the string contains any half-width chars. Empty string is valid. -func IsHalfWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) -} - -// IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid. -func IsVariableWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) -} - -// IsBase64 check if a string is base64 encoded. -func IsBase64(str string) bool { - return rxBase64.MatchString(str) -} - -// IsFilePath check is a string is Win or Unix file path and returns it's type. -func IsFilePath(str string) (bool, int) { - if rxWinPath.MatchString(str) { - //check windows path limit see: - // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath - if len(str[3:]) > 32767 { - return false, Win - } - return true, Win - } else if rxUnixPath.MatchString(str) { - return true, Unix - } - return false, Unknown -} - -// IsDataURI checks if a string is base64 encoded data URI such as an image -func IsDataURI(str string) bool { - dataURI := strings.Split(str, ",") - if !rxDataURI.MatchString(dataURI[0]) { - return false - } - return IsBase64(dataURI[1]) -} - -// IsISO3166Alpha2 checks if a string is valid two-letter country code -func IsISO3166Alpha2(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO3166Alpha3 checks if a string is valid three-letter country code -func IsISO3166Alpha3(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha3Code { - return true - } - } - return false -} - -// IsISO693Alpha2 checks if a string is valid two-letter language code -func IsISO693Alpha2(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO693Alpha3b checks if a string is valid three-letter language code -func IsISO693Alpha3b(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha3bCode { - return true - } - } - return false -} - -// IsDNSName will validate the given string as a DNS name -func IsDNSName(str string) bool { - if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { - // constraints already violated - return false - } - return !IsIP(str) && rxDNSName.MatchString(str) -} - -// IsHash checks if a string is a hash of type algorithm. -// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] -func IsHash(str string, algorithm string) bool { - len := "0" - algo := strings.ToLower(algorithm) - - if algo == "crc32" || algo == "crc32b" { - len = "8" - } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { - len = "32" - } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { - len = "40" - } else if algo == "tiger192" { - len = "48" - } else if algo == "sha256" { - len = "64" - } else if algo == "sha384" { - len = "96" - } else if algo == "sha512" { - len = "128" - } else { - return false - } - - return Matches(str, "^[a-f0-9]{"+len+"}$") -} - -// IsDialString validates the given string for usage with the various Dial() functions -func IsDialString(str string) bool { - - if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { - return true - } - - return false -} - -// IsIP checks if a string is either IP version 4 or 6. -func IsIP(str string) bool { - return net.ParseIP(str) != nil -} - -// IsPort checks if a string represents a valid port -func IsPort(str string) bool { - if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { - return true - } - return false -} - -// IsIPv4 check if the string is an IP version 4. -func IsIPv4(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ".") -} - -// IsIPv6 check if the string is an IP version 6. -func IsIPv6(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ":") -} - -// IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6) -func IsCIDR(str string) bool { - _, _, err := net.ParseCIDR(str) - return err == nil -} - -// IsMAC check if a string is valid MAC address. -// Possible MAC formats: -// 01:23:45:67:89:ab -// 01:23:45:67:89:ab:cd:ef -// 01-23-45-67-89-ab -// 01-23-45-67-89-ab-cd-ef -// 0123.4567.89ab -// 0123.4567.89ab.cdef -func IsMAC(str string) bool { - _, err := net.ParseMAC(str) - return err == nil -} - -// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name -func IsHost(str string) bool { - return IsIP(str) || IsDNSName(str) -} - -// IsMongoID check if the string is a valid hex-encoded representation of a MongoDB ObjectId. -func IsMongoID(str string) bool { - return rxHexadecimal.MatchString(str) && (len(str) == 24) -} - -// IsLatitude check if a string is valid latitude. -func IsLatitude(str string) bool { - return rxLatitude.MatchString(str) -} - -// IsLongitude check if a string is valid longitude. -func IsLongitude(str string) bool { - return rxLongitude.MatchString(str) -} - -// IsRsaPublicKey check if a string is valid public key with provided length -func IsRsaPublicKey(str string, keylen int) bool { - bb := bytes.NewBufferString(str) - pemBytes, err := ioutil.ReadAll(bb) - if err != nil { - return false - } - block, _ := pem.Decode(pemBytes) - if block != nil && block.Type != "PUBLIC KEY" { - return false - } - var der []byte - - if block != nil { - der = block.Bytes - } else { - der, err = base64.StdEncoding.DecodeString(str) - if err != nil { - return false - } - } - - key, err := x509.ParsePKIXPublicKey(der) - if err != nil { - return false - } - pubkey, ok := key.(*rsa.PublicKey) - if !ok { - return false - } - bitlen := len(pubkey.N.Bytes()) * 8 - return bitlen == int(keylen) -} - -func toJSONName(tag string) string { - if tag == "" { - return "" - } - - // JSON name always comes first. If there's no options then split[0] is - // JSON name, if JSON name is not set, then split[0] is an empty string. - split := strings.SplitN(tag, ",", 2) - - name := split[0] - - // However it is possible that the field is skipped when - // (de-)serializing from/to JSON, in which case assume that there is no - // tag name to use - if name == "-" { - return "" - } - return name -} - -func PrependPathToErrors(err error, path string) error { - switch err2 := err.(type) { - case Error: - err2.Path = append([]string{path}, err2.Path...) - return err2 - case Errors: - errors := err2.Errors() - for i, err3 := range errors { - errors[i] = PrependPathToErrors(err3, path) - } - return err2 - } - fmt.Println(err) - return err -} - -// ValidateStruct use tags for fields. -// result will be equal to `false` if there are any errors. -func ValidateStruct(s interface{}) (bool, error) { - if s == nil { - return true, nil - } - result := true - var err error - val := reflect.ValueOf(s) - if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { - val = val.Elem() - } - // we only accept structs - if val.Kind() != reflect.Struct { - return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) - } - var errs Errors - for i := 0; i < val.NumField(); i++ { - valueField := val.Field(i) - typeField := val.Type().Field(i) - if typeField.PkgPath != "" { - continue // Private field - } - structResult := true - if valueField.Kind() == reflect.Interface { - valueField = valueField.Elem() - } - if (valueField.Kind() == reflect.Struct || - (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - typeField.Tag.Get(tagName) != "-" { - var err error - structResult, err = ValidateStruct(valueField.Interface()) - if err != nil { - err = PrependPathToErrors(err, typeField.Name) - errs = append(errs, err) - } - } - resultField, err2 := typeCheck(valueField, typeField, val, nil) - if err2 != nil { - - // Replace structure name with JSON name if there is a tag on the variable - jsonTag := toJSONName(typeField.Tag.Get("json")) - if jsonTag != "" { - switch jsonError := err2.(type) { - case Error: - jsonError.Name = jsonTag - err2 = jsonError - case Errors: - for i2, err3 := range jsonError { - switch customErr := err3.(type) { - case Error: - customErr.Name = jsonTag - jsonError[i2] = customErr - } - } - - err2 = jsonError - } - } - - errs = append(errs, err2) - } - result = result && resultField && structResult - } - if len(errs) > 0 { - err = errs - } - return result, err -} - -// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} -func parseTagIntoMap(tag string) tagOptionsMap { - optionsMap := make(tagOptionsMap) - options := strings.Split(tag, ",") - - for i, option := range options { - option = strings.TrimSpace(option) - - validationOptions := strings.Split(option, "~") - if !isValidTag(validationOptions[0]) { - continue - } - if len(validationOptions) == 2 { - optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i} - } else { - optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i} - } - } - return optionsMap -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -// IsSSN will validate the given string as a U.S. Social Security Number -func IsSSN(str string) bool { - if str == "" || len(str) != 11 { - return false - } - return rxSSN.MatchString(str) -} - -// IsSemver check if string is valid semantic version -func IsSemver(str string) bool { - return rxSemver.MatchString(str) -} - -// IsTime check if string is valid according to given format -func IsTime(str string, format string) bool { - _, err := time.Parse(format, str) - return err == nil -} - -// IsRFC3339 check if string is valid timestamp value according to RFC3339 -func IsRFC3339(str string) bool { - return IsTime(str, time.RFC3339) -} - -// IsRFC3339WithoutZone check if string is valid timestamp value according to RFC3339 which excludes the timezone. -func IsRFC3339WithoutZone(str string) bool { - return IsTime(str, RF3339WithoutZone) -} - -// IsISO4217 check if string is valid ISO currency code -func IsISO4217(str string) bool { - for _, currency := range ISO4217List { - if str == currency { - return true - } - } - - return false -} - -// ByteLength check string's length -func ByteLength(str string, params ...string) bool { - if len(params) == 2 { - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return len(str) >= int(min) && len(str) <= int(max) - } - - return false -} - -// RuneLength check string's length -// Alias for StringLength -func RuneLength(str string, params ...string) bool { - return StringLength(str, params...) -} - -// IsRsaPub check whether string is valid RSA key -// Alias for IsRsaPublicKey -func IsRsaPub(str string, params ...string) bool { - if len(params) == 1 { - len, _ := ToInt(params[0]) - return IsRsaPublicKey(str, int(len)) - } - - return false -} - -// StringMatches checks if a string matches a given pattern. -func StringMatches(s string, params ...string) bool { - if len(params) == 1 { - pattern := params[0] - return Matches(s, pattern) - } - return false -} - -// StringLength check string's length (including multi byte strings) -func StringLength(str string, params ...string) bool { - - if len(params) == 2 { - strLength := utf8.RuneCountInString(str) - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return strLength >= int(min) && strLength <= int(max) - } - - return false -} - -// Range check string's length -func Range(str string, params ...string) bool { - if len(params) == 2 { - value, _ := ToFloat(str) - min, _ := ToFloat(params[0]) - max, _ := ToFloat(params[1]) - return InRange(value, min, max) - } - - return false -} - -func isInRaw(str string, params ...string) bool { - if len(params) == 1 { - rawParams := params[0] - - parsedParams := strings.Split(rawParams, "|") - - return IsIn(str, parsedParams...) - } - - return false -} - -// IsIn check if string str is a member of the set of strings params -func IsIn(str string, params ...string) bool { - for _, param := range params { - if str == param { - return true - } - } - - return false -} - -func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { - if nilPtrAllowedByRequired { - k := v.Kind() - if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() { - return true, nil - } - } - - if requiredOption, isRequired := options["required"]; isRequired { - if len(requiredOption.customErrorMessage) > 0 { - return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}} - } - return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}} - } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { - return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}} - } - // not required and empty is valid - return true, nil -} - -func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { - if !v.IsValid() { - return false, nil - } - - tag := t.Tag.Get(tagName) - - // Check if the field should be ignored - switch tag { - case "": - if v.Kind() != reflect.Slice && v.Kind() != reflect.Map { - if !fieldsRequiredByDefault { - return true, nil - } - return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}} - } - case "-": - return true, nil - } - - isRootType := false - if options == nil { - isRootType = true - options = parseTagIntoMap(tag) - } - - if isEmptyValue(v) { - // an empty value is not validated, check only required - isValid, resultErr = checkRequired(v, t, options) - for key := range options { - delete(options, key) - } - return isValid, resultErr - } - - var customTypeErrors Errors - optionsOrder := options.orderedKeys() - for _, validatorName := range optionsOrder { - validatorStruct := options[validatorName] - if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { - delete(options, validatorName) - - if result := validatefunc(v.Interface(), o.Interface()); !result { - if len(validatorStruct.customErrorMessage) > 0 { - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) - continue - } - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) - } - } - } - - if len(customTypeErrors.Errors()) > 0 { - return false, customTypeErrors - } - - if isRootType { - // Ensure that we've checked the value by all specified validators before report that the value is valid - defer func() { - delete(options, "optional") - delete(options, "required") - - if isValid && resultErr == nil && len(options) != 0 { - optionsOrder := options.orderedKeys() - for _, validator := range optionsOrder { - isValid = false - resultErr = Error{t.Name, fmt.Errorf( - "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}} - return - } - } - }() - } - - switch v.Kind() { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, - reflect.Float32, reflect.Float64, - reflect.String: - // for each tag option check the map of validator functions - for _, validatorSpec := range optionsOrder { - validatorStruct := options[validatorSpec] - var negate bool - validator := validatorSpec - customMsgExists := len(validatorStruct.customErrorMessage) > 0 - - // Check whether the tag looks like '!something' or 'something' - if validator[0] == '!' { - validator = validator[1:] - negate = true - } - - // Check for param validators - for key, value := range ParamTagRegexMap { - ps := value.FindStringSubmatch(validator) - if len(ps) == 0 { - continue - } - - validatefunc, ok := ParamTagMap[key] - if !ok { - continue - } - - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { - if customMsgExists { - return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - default: - // type not yet supported, fail - return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}} - } - } - - if validatefunc, ok := TagMap[validator]; ok { - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field); !result && !negate || result && negate { - if customMsgExists { - return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - default: - //Not Yet Supported Types (Fail here!) - err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) - return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}} - } - } - } - return true, nil - case reflect.Map: - if v.Type().Key().Kind() != reflect.String { - return false, &UnsupportedTypeError{v.Type()} - } - var sv stringValues - sv = v.MapKeys() - sort.Sort(sv) - result := true - for i, k := range sv { - var resultItem bool - var err error - if v.MapIndex(k).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.MapIndex(k), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) - if err != nil { - err = PrependPathToErrors(err, t.Name+"."+sv[i].Interface().(string)) - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Slice, reflect.Array: - result := true - for i := 0; i < v.Len(); i++ { - var resultItem bool - var err error - if v.Index(i).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.Index(i), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.Index(i).Interface()) - if err != nil { - err = PrependPathToErrors(err, t.Name+"."+strconv.Itoa(i)) - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Interface: - // If the value is an interface then encode its element - if v.IsNil() { - return true, nil - } - return ValidateStruct(v.Interface()) - case reflect.Ptr: - // If the value is a pointer then check its element - if v.IsNil() { - return true, nil - } - return typeCheck(v.Elem(), t, o, options) - case reflect.Struct: - return ValidateStruct(v.Interface()) - default: - return false, &UnsupportedTypeError{v.Type()} - } -} - -func stripParams(validatorString string) string { - return paramsRegexp.ReplaceAllString(validatorString, "") -} - -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.String, reflect.Array: - return v.Len() == 0 - case reflect.Map, reflect.Slice: - return v.Len() == 0 || v.IsNil() - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) -} - -// ErrorByField returns error for specified field of the struct -// validated by ValidateStruct or empty string if there are no errors -// or this field doesn't exists or doesn't have any errors. -func ErrorByField(e error, field string) string { - if e == nil { - return "" - } - return ErrorsByField(e)[field] -} - -// ErrorsByField returns map of errors of the struct validated -// by ValidateStruct or empty map if there are no errors. -func ErrorsByField(e error) map[string]string { - m := make(map[string]string) - if e == nil { - return m - } - // prototype for ValidateStruct - - switch e.(type) { - case Error: - m[e.(Error).Name] = e.(Error).Err.Error() - case Errors: - for _, item := range e.(Errors).Errors() { - n := ErrorsByField(item) - for k, v := range n { - m[k] = v - } - } - } - - return m -} - -// Error returns string equivalent for reflect.Type -func (e *UnsupportedTypeError) Error() string { - return "validator: unsupported type: " + e.Type.String() -} - -func (sv stringValues) Len() int { return len(sv) } -func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } -func (sv stringValues) get(i int) string { return sv[i].String() } diff --git a/e2e/vendor/github.com/asaskevich/govalidator/wercker.yml b/e2e/vendor/github.com/asaskevich/govalidator/wercker.yml deleted file mode 100644 index cac7a5fcf..000000000 --- a/e2e/vendor/github.com/asaskevich/govalidator/wercker.yml +++ /dev/null @@ -1,15 +0,0 @@ -box: golang -build: - steps: - - setup-go-workspace - - - script: - name: go get - code: | - go version - go get -t ./... - - - script: - name: go test - code: | - go test -race ./... diff --git a/e2e/vendor/github.com/google/cel-go/cel/env.go b/e2e/vendor/github.com/google/cel-go/cel/env.go index ab736b776..3bfe42899 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/env.go +++ b/e2e/vendor/github.com/google/cel-go/cel/env.go @@ -217,7 +217,7 @@ func (e *Env) Check(ast *Ast) (*Ast, *Issues) { chk, err := e.initChecker() if err != nil { errs := common.NewErrors(ast.Source()) - errs.ReportError(common.NoLocation, err.Error()) + errs.ReportErrorString(common.NoLocation, err.Error()) return nil, NewIssuesWithSourceInfo(errs, ast.NativeRep().SourceInfo()) } @@ -556,7 +556,8 @@ func (e *Env) PartialVars(vars any) (interpreter.PartialActivation, error) { // TODO: Consider adding an option to generate a Program.Residual to avoid round-tripping to an // Ast format and then Program again. func (e *Env) ResidualAst(a *Ast, details *EvalDetails) (*Ast, error) { - pruned := interpreter.PruneAst(a.impl.Expr(), a.impl.SourceInfo().MacroCalls(), details.State()) + ast := a.NativeRep() + pruned := interpreter.PruneAst(ast.Expr(), ast.SourceInfo().MacroCalls(), details.State()) newAST := &Ast{source: a.Source(), impl: pruned} expr, err := AstToString(newAST) if err != nil { @@ -582,7 +583,7 @@ func (e *Env) EstimateCost(ast *Ast, estimator checker.CostEstimator, opts ...ch extendedOpts := make([]checker.CostOption, 0, len(e.costOptions)) extendedOpts = append(extendedOpts, opts...) extendedOpts = append(extendedOpts, e.costOptions...) - return checker.Cost(ast.impl, estimator, extendedOpts...) + return checker.Cost(ast.NativeRep(), estimator, extendedOpts...) } // configure applies a series of EnvOptions to the current environment. @@ -614,6 +615,9 @@ func (e *Env) configure(opts []EnvOption) (*Env, error) { if e.HasFeature(featureVariadicLogicalASTs) { prsrOpts = append(prsrOpts, parser.EnableVariadicOperatorASTs(true)) } + if e.HasFeature(featureIdentEscapeSyntax) { + prsrOpts = append(prsrOpts, parser.EnableIdentEscapeSyntax(true)) + } e.prsr, err = parser.NewParser(prsrOpts...) if err != nil { return nil, err diff --git a/e2e/vendor/github.com/google/cel-go/cel/inlining.go b/e2e/vendor/github.com/google/cel-go/cel/inlining.go index 78d5bea65..a4530e19e 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/inlining.go +++ b/e2e/vendor/github.com/google/cel-go/cel/inlining.go @@ -60,7 +60,7 @@ func NewInlineVariable(name string, definition *Ast) *InlineVariable { // If the variable occurs more than once, the provided alias will be used to replace the expressions // where the variable name occurs. func NewInlineVariableWithAlias(name, alias string, definition *Ast) *InlineVariable { - return &InlineVariable{name: name, alias: alias, def: definition.impl} + return &InlineVariable{name: name, alias: alias, def: definition.NativeRep()} } // NewInliningOptimizer creates and optimizer which replaces variables with expression definitions. diff --git a/e2e/vendor/github.com/google/cel-go/cel/io.go b/e2e/vendor/github.com/google/cel-go/cel/io.go index 7d08d1c81..a327c9672 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/io.go +++ b/e2e/vendor/github.com/google/cel-go/cel/io.go @@ -62,7 +62,7 @@ func AstToCheckedExpr(a *Ast) (*exprpb.CheckedExpr, error) { if !a.IsChecked() { return nil, fmt.Errorf("cannot convert unchecked ast") } - return ast.ToProto(a.impl) + return ast.ToProto(a.NativeRep()) } // ParsedExprToAst converts a parsed expression proto message to an Ast. @@ -99,15 +99,17 @@ func AstToParsedExpr(a *Ast) (*exprpb.ParsedExpr, error) { // Note, the conversion may not be an exact replica of the original expression, but will produce // a string that is semantically equivalent and whose textual representation is stable. func AstToString(a *Ast) (string, error) { - return parser.Unparse(a.impl.Expr(), a.impl.SourceInfo()) + return parser.Unparse(a.NativeRep().Expr(), a.NativeRep().SourceInfo()) } -// RefValueToValue converts between ref.Val and api.expr.Value. +// RefValueToValue converts between ref.Val and google.api.expr.v1alpha1.Value. // The result Value is the serialized proto form. The ref.Val must not be error or unknown. func RefValueToValue(res ref.Val) (*exprpb.Value, error) { return ValueAsAlphaProto(res) } +// ValueAsAlphaProto converts between ref.Val and google.api.expr.v1alpha1.Value. +// The result Value is the serialized proto form. The ref.Val must not be error or unknown. func ValueAsAlphaProto(res ref.Val) (*exprpb.Value, error) { canonical, err := ValueAsProto(res) if err != nil { @@ -118,6 +120,8 @@ func ValueAsAlphaProto(res ref.Val) (*exprpb.Value, error) { return alpha, err } +// ValueAsProto converts between ref.Val and cel.expr.Value. +// The result Value is the serialized proto form. The ref.Val must not be error or unknown. func ValueAsProto(res ref.Val) (*celpb.Value, error) { switch res.Type() { case types.BoolType: @@ -205,11 +209,12 @@ var ( anyPbType = reflect.TypeOf(&anypb.Any{}) ) -// ValueToRefValue converts between exprpb.Value and ref.Val. +// ValueToRefValue converts between google.api.expr.v1alpha1.Value and ref.Val. func ValueToRefValue(adapter types.Adapter, v *exprpb.Value) (ref.Val, error) { return AlphaProtoAsValue(adapter, v) } +// AlphaProtoAsValue converts between google.api.expr.v1alpha1.Value and ref.Val. func AlphaProtoAsValue(adapter types.Adapter, v *exprpb.Value) (ref.Val, error) { canonical := &celpb.Value{} if err := convertProto(v, canonical); err != nil { @@ -218,6 +223,7 @@ func AlphaProtoAsValue(adapter types.Adapter, v *exprpb.Value) (ref.Val, error) return ProtoAsValue(adapter, canonical) } +// ProtoAsValue converts between cel.expr.Value and ref.Val. func ProtoAsValue(adapter types.Adapter, v *celpb.Value) (ref.Val, error) { switch v.Kind.(type) { case *celpb.Value_NullValue: diff --git a/e2e/vendor/github.com/google/cel-go/cel/library.go b/e2e/vendor/github.com/google/cel-go/cel/library.go index be59f1b02..c0aef5019 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/library.go +++ b/e2e/vendor/github.com/google/cel-go/cel/library.go @@ -15,6 +15,7 @@ package cel import ( + "fmt" "math" "strconv" "strings" @@ -35,9 +36,11 @@ const ( optMapMacro = "optMap" optFlatMapMacro = "optFlatMap" hasValueFunc = "hasValue" + unwrapOptFunc = "unwrapOpt" optionalNoneFunc = "optional.none" optionalOfFunc = "optional.of" optionalOfNonZeroValueFunc = "optional.ofNonZeroValue" + optionalUnwrapFunc = "optional.unwrap" valueFunc = "value" unusedIterVar = "#unused" ) @@ -260,6 +263,37 @@ func (stdLibrary) ProgramOptions() []ProgramOption { // be expressed with `optMap`. // // msg.?elements.optFlatMap(e, e[?0]) // return the first element if present. + +// # First +// +// Introduced in version: 2 +// +// Returns an optional with the first value from the right hand list, or +// optional.None. +// +// [1, 2, 3].first().value() == 1 + +// # Last +// +// Introduced in version: 2 +// +// Returns an optional with the last value from the right hand list, or +// optional.None. +// +// [1, 2, 3].last().value() == 3 +// +// This is syntactic sugar for msg.elements[msg.elements.size()-1]. + +// # Unwrap / UnwrapOpt +// +// Introduced in version: 2 +// +// Returns a list of all the values that are not none in the input list of optional values. +// Can be used as optional.unwrap(List[T]) or with postfix notation: List[T].unwrapOpt() +// +// optional.unwrap([optional.of(42), optional.none()]) == [42] +// [optional.of(42), optional.none()].unwrapOpt() == [42] + func OptionalTypes(opts ...OptionalTypesOption) EnvOption { lib := &optionalLib{version: math.MaxUint32} for _, opt := range opts { @@ -303,6 +337,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption { optionalTypeV := OptionalType(paramTypeV) listTypeV := ListType(paramTypeV) mapTypeKV := MapType(paramTypeK, paramTypeV) + listOptionalTypeV := ListType(optionalTypeV) opts := []EnvOption{ // Enable the optional syntax in the parser. @@ -375,6 +410,46 @@ func (lib *optionalLib) CompileOptions() []EnvOption { if lib.version >= 1 { opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap))) } + + if lib.version >= 2 { + opts = append(opts, Function("last", + MemberOverload("list_last", []*Type{listTypeV}, optionalTypeV, + UnaryBinding(func(v ref.Val) ref.Val { + list := v.(traits.Lister) + sz := list.Size().Value().(int64) + + if sz == 0 { + return types.OptionalNone + } + + return types.OptionalOf(list.Get(types.Int(sz - 1))) + }), + ), + )) + + opts = append(opts, Function("first", + MemberOverload("list_first", []*Type{listTypeV}, optionalTypeV, + UnaryBinding(func(v ref.Val) ref.Val { + list := v.(traits.Lister) + sz := list.Size().Value().(int64) + + if sz == 0 { + return types.OptionalNone + } + + return types.OptionalOf(list.Get(types.Int(0))) + }), + ), + )) + + opts = append(opts, Function(optionalUnwrapFunc, + Overload("optional_unwrap", []*Type{listOptionalTypeV}, listTypeV, + UnaryBinding(optUnwrap)))) + opts = append(opts, Function(unwrapOptFunc, + MemberOverload("optional_unwrapOpt", []*Type{listOptionalTypeV}, listTypeV, + UnaryBinding(optUnwrap)))) + } + return opts } @@ -439,6 +514,23 @@ func optFlatMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Exp ), nil } +func optUnwrap(value ref.Val) ref.Val { + list := value.(traits.Lister) + var unwrappedList []ref.Val + iter := list.Iterator() + for iter.HasNext() == types.True { + val := iter.Next() + opt, isOpt := val.(*types.Optional) + if !isOpt { + return types.WrapErr(fmt.Errorf("value %v is not optional", val)) + } + if opt.HasValue() { + unwrappedList = append(unwrappedList, opt.GetValue()) + } + } + return types.DefaultTypeAdapter.NativeToValue(unwrappedList) +} + func enableOptionalSyntax() EnvOption { return func(e *Env) (*Env, error) { e.prsrOpts = append(e.prsrOpts, parser.EnableOptionalSyntax(true)) @@ -677,7 +769,7 @@ var ( func timestampGetFullYear(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Year()) } @@ -685,7 +777,7 @@ func timestampGetFullYear(ts, tz ref.Val) ref.Val { func timestampGetMonth(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } // CEL spec indicates that the month should be 0-based, but the Time value // for Month() is 1-based. @@ -695,7 +787,7 @@ func timestampGetMonth(ts, tz ref.Val) ref.Val { func timestampGetDayOfYear(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.YearDay() - 1) } @@ -703,7 +795,7 @@ func timestampGetDayOfYear(ts, tz ref.Val) ref.Val { func timestampGetDayOfMonthZeroBased(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Day() - 1) } @@ -711,7 +803,7 @@ func timestampGetDayOfMonthZeroBased(ts, tz ref.Val) ref.Val { func timestampGetDayOfMonthOneBased(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Day()) } @@ -719,7 +811,7 @@ func timestampGetDayOfMonthOneBased(ts, tz ref.Val) ref.Val { func timestampGetDayOfWeek(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Weekday()) } @@ -727,7 +819,7 @@ func timestampGetDayOfWeek(ts, tz ref.Val) ref.Val { func timestampGetHours(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Hour()) } @@ -735,7 +827,7 @@ func timestampGetHours(ts, tz ref.Val) ref.Val { func timestampGetMinutes(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Minute()) } @@ -743,7 +835,7 @@ func timestampGetMinutes(ts, tz ref.Val) ref.Val { func timestampGetSeconds(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Second()) } @@ -751,7 +843,7 @@ func timestampGetSeconds(ts, tz ref.Val) ref.Val { func timestampGetMilliseconds(ts, tz ref.Val) ref.Val { t, err := inTimeZone(ts, tz) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(t.Nanosecond() / 1000000) } diff --git a/e2e/vendor/github.com/google/cel-go/cel/optimizer.go b/e2e/vendor/github.com/google/cel-go/cel/optimizer.go index c149abb70..9a2a97a64 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/optimizer.go +++ b/e2e/vendor/github.com/google/cel-go/cel/optimizer.go @@ -48,8 +48,8 @@ func NewStaticOptimizer(optimizers ...ASTOptimizer) *StaticOptimizer { // If issues are encountered, the Issues.Err() return value will be non-nil. func (opt *StaticOptimizer) Optimize(env *Env, a *Ast) (*Ast, *Issues) { // Make a copy of the AST to be optimized. - optimized := ast.Copy(a.impl) - ids := newIDGenerator(ast.MaxID(a.impl)) + optimized := ast.Copy(a.NativeRep()) + ids := newIDGenerator(ast.MaxID(a.NativeRep())) // Create the optimizer context, could be pooled in the future. issues := NewIssues(common.NewErrors(a.Source())) @@ -86,7 +86,7 @@ func (opt *StaticOptimizer) Optimize(env *Env, a *Ast) (*Ast, *Issues) { if iss.Err() != nil { return nil, iss } - optimized = checked.impl + optimized = checked.NativeRep() } // Return the optimized result. diff --git a/e2e/vendor/github.com/google/cel-go/cel/options.go b/e2e/vendor/github.com/google/cel-go/cel/options.go index 69c694263..85f777e95 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/options.go +++ b/e2e/vendor/github.com/google/cel-go/cel/options.go @@ -65,6 +65,9 @@ const ( // Enable error generation when a presence test or optional field selection is // performed on a primitive type. featureEnableErrorOnBadPresenceTest + + // Enable escape syntax for field identifiers (`). + featureIdentEscapeSyntax ) // EnvOption is a functional interface for configuring the environment. @@ -618,6 +621,12 @@ func EnableMacroCallTracking() EnvOption { return features(featureEnableMacroCallTracking, true) } +// EnableIdentifierEscapeSyntax enables identifier escaping (`) syntax for +// fields. +func EnableIdentifierEscapeSyntax() EnvOption { + return features(featureIdentEscapeSyntax, true) +} + // CrossTypeNumericComparisons makes it possible to compare across numeric types, e.g. double < int func CrossTypeNumericComparisons(enabled bool) EnvOption { return features(featureCrossTypeNumericComparisons, enabled) @@ -655,6 +664,15 @@ func ParserExpressionSizeLimit(limit int) EnvOption { } } +// EnableHiddenAccumulatorName sets the parser to use the identifier '@result' for accumulators +// which is not normally accessible from CEL source. +func EnableHiddenAccumulatorName(enabled bool) EnvOption { + return func(e *Env) (*Env, error) { + e.prsrOpts = append(e.prsrOpts, parser.EnableHiddenAccumulatorName(enabled)) + return e, nil + } +} + func maybeInteropProvider(provider any) (types.Provider, error) { switch p := provider.(type) { case types.Provider: diff --git a/e2e/vendor/github.com/google/cel-go/cel/program.go b/e2e/vendor/github.com/google/cel-go/cel/program.go index 6f477afc9..49bd53783 100644 --- a/e2e/vendor/github.com/google/cel-go/cel/program.go +++ b/e2e/vendor/github.com/google/cel-go/cel/program.go @@ -100,6 +100,9 @@ type EvalDetails struct { // State of the evaluation, non-nil if the OptTrackState or OptExhaustiveEval is specified // within EvalOptions. func (ed *EvalDetails) State() interpreter.EvalState { + if ed == nil { + return interpreter.NewEvalState() + } return ed.state } diff --git a/e2e/vendor/github.com/google/cel-go/checker/checker.go b/e2e/vendor/github.com/google/cel-go/checker/checker.go index 0603cfa30..6824af7a5 100644 --- a/e2e/vendor/github.com/google/cel-go/checker/checker.go +++ b/e2e/vendor/github.com/google/cel-go/checker/checker.go @@ -529,9 +529,15 @@ func (c *checker) checkComprehension(e ast.Expr) { c.isAssignable(types.DynType, rangeType) // Set the range iteration variable to type DYN as well. varType = types.DynType + if comp.HasIterVar2() { + var2Type = types.DynType + } default: c.errors.notAComprehensionRange(comp.IterRange().ID(), c.location(comp.IterRange()), rangeType) varType = types.ErrorType + if comp.HasIterVar2() { + var2Type = types.ErrorType + } } // Create a block scope for the loop. diff --git a/e2e/vendor/github.com/google/cel-go/checker/cost.go b/e2e/vendor/github.com/google/cel-go/checker/cost.go index 04244694d..59be751c9 100644 --- a/e2e/vendor/github.com/google/cel-go/checker/cost.go +++ b/e2e/vendor/github.com/google/cel-go/checker/cost.go @@ -28,15 +28,20 @@ import ( // CostEstimator estimates the sizes of variable length input data and the costs of functions. type CostEstimator interface { - // EstimateSize returns a SizeEstimate for the given AstNode, or nil if - // the estimator has no estimate to provide. The size is equivalent to the result of the CEL `size()` function: - // length of strings and bytes, number of map entries or number of list items. - // EstimateSize is only called for AstNodes where - // CEL does not know the size; EstimateSize is not called for values defined inline in CEL where the size - // is already obvious to CEL. + // EstimateSize returns a SizeEstimate for the given AstNode, or nil if the estimator has no + // estimate to provide. + // + // The size is equivalent to the result of the CEL `size()` function: + // * Number of unicode characters in a string + // * Number of bytes in a sequence + // * Number of map entries or number of list items. + // + // EstimateSize is only called for AstNodes where CEL does not know the size; EstimateSize is not + // called for values defined inline in CEL where the size is already obvious to CEL. EstimateSize(element AstNode) *SizeEstimate - // EstimateCallCost returns the estimated cost of an invocation, or nil if - // the estimator has no estimate to provide. + + // EstimateCallCost returns the estimated cost of an invocation, or nil if the estimator has no + // estimate to provide. EstimateCallCost(function, overloadID string, target *AstNode, args []AstNode) *CallEstimate } @@ -44,6 +49,7 @@ type CostEstimator interface { // The ResultSize should only be provided if the call results in a map, list, string or bytes. type CallEstimate struct { CostEstimate + ResultSize *SizeEstimate } @@ -53,10 +59,13 @@ type AstNode interface { // represent type directly reachable from the provided type declarations. // The first path element is a variable. All subsequent path elements are one of: field name, '@items', '@keys', '@values'. Path() []string + // Type returns the deduced type of the AstNode. Type() *types.Type + // Expr returns the expression of the AstNode. Expr() ast.Expr + // ComputedSize returns a size estimate of the AstNode derived from information available in the CEL expression. // For constants and inline list and map declarations, the exact size is returned. For concatenated list, strings // and bytes, the size is derived from the size estimates of the operands. nil is returned if there is no @@ -84,36 +93,7 @@ func (e astNode) Expr() ast.Expr { } func (e astNode) ComputedSize() *SizeEstimate { - if e.derivedSize != nil { - return e.derivedSize - } - var v uint64 - switch e.expr.Kind() { - case ast.LiteralKind: - switch ck := e.expr.AsLiteral().(type) { - case types.String: - // converting to runes here is an O(n) operation, but - // this is consistent with how size is computed at runtime, - // and how the language definition defines string size - v = uint64(len([]rune(ck))) - case types.Bytes: - v = uint64(len(ck)) - case types.Bool, types.Double, types.Duration, - types.Int, types.Timestamp, types.Uint, - types.Null: - v = uint64(1) - default: - return nil - } - case ast.ListKind: - v = uint64(e.expr.AsList().Size()) - case ast.MapKind: - v = uint64(e.expr.AsMap().Size()) - default: - return nil - } - - return &SizeEstimate{Min: v, Max: v} + return e.derivedSize } // SizeEstimate represents an estimated size of a variable length string, bytes, map or list. @@ -121,6 +101,16 @@ type SizeEstimate struct { Min, Max uint64 } +// UnknownSizeEstimate returns a size between 0 and max uint +func UnknownSizeEstimate() SizeEstimate { + return unknownSizeEstimate +} + +// FixedSizeEstimate returns a size estimate with a fixed min and max range. +func FixedSizeEstimate(size uint64) SizeEstimate { + return SizeEstimate{Min: size, Max: size} +} + // Add adds to another SizeEstimate and returns the sum. // If add would result in an uint64 overflow, the result is math.MaxUint64. func (se SizeEstimate) Add(sizeEstimate SizeEstimate) SizeEstimate { @@ -175,12 +165,22 @@ type CostEstimate struct { Min, Max uint64 } +// UnknownCostEstimate returns a cost with an unknown impact. +func UnknownCostEstimate() CostEstimate { + return unknownCostEstimate +} + +// FixedCostEstimate returns a cost with a fixed min and max range. +func FixedCostEstimate(cost uint64) CostEstimate { + return CostEstimate{Min: cost, Max: cost} +} + // Add adds the costs and returns the sum. // If add would result in an uint64 overflow for the min or max, the value is set to math.MaxUint64. func (ce CostEstimate) Add(cost CostEstimate) CostEstimate { return CostEstimate{ - addUint64NoOverflow(ce.Min, cost.Min), - addUint64NoOverflow(ce.Max, cost.Max), + Min: addUint64NoOverflow(ce.Min, cost.Min), + Max: addUint64NoOverflow(ce.Max, cost.Max), } } @@ -188,8 +188,8 @@ func (ce CostEstimate) Add(cost CostEstimate) CostEstimate { // If multiply would result in an uint64 overflow, the result is math.MaxUint64. func (ce CostEstimate) Multiply(cost CostEstimate) CostEstimate { return CostEstimate{ - multiplyUint64NoOverflow(ce.Min, cost.Min), - multiplyUint64NoOverflow(ce.Max, cost.Max), + Min: multiplyUint64NoOverflow(ce.Min, cost.Min), + Max: multiplyUint64NoOverflow(ce.Max, cost.Max), } } @@ -197,8 +197,8 @@ func (ce CostEstimate) Multiply(cost CostEstimate) CostEstimate { // nearest integer of the result, rounded up. func (ce CostEstimate) MultiplyByCostFactor(costPerUnit float64) CostEstimate { return CostEstimate{ - multiplyByCostFactor(ce.Min, costPerUnit), - multiplyByCostFactor(ce.Max, costPerUnit), + Min: multiplyByCostFactor(ce.Min, costPerUnit), + Max: multiplyByCostFactor(ce.Max, costPerUnit), } } @@ -245,49 +245,6 @@ func multiplyByCostFactor(x uint64, y float64) uint64 { return uint64(ceil) } -var ( - selectAndIdentCost = CostEstimate{Min: common.SelectAndIdentCost, Max: common.SelectAndIdentCost} - constCost = CostEstimate{Min: common.ConstCost, Max: common.ConstCost} - - createListBaseCost = CostEstimate{Min: common.ListCreateBaseCost, Max: common.ListCreateBaseCost} - createMapBaseCost = CostEstimate{Min: common.MapCreateBaseCost, Max: common.MapCreateBaseCost} - createMessageBaseCost = CostEstimate{Min: common.StructCreateBaseCost, Max: common.StructCreateBaseCost} -) - -type coster struct { - // exprPath maps from Expr Id to field path. - exprPath map[int64][]string - // iterRanges tracks the iterRange of each iterVar. - iterRanges iterRangeScopes - // computedSizes tracks the computed sizes of call results. - computedSizes map[int64]SizeEstimate - checkedAST *ast.AST - estimator CostEstimator - overloadEstimators map[string]FunctionEstimator - // presenceTestCost will either be a zero or one based on whether has() macros count against cost computations. - presenceTestCost CostEstimate -} - -// Use a stack of iterVar -> iterRange Expr Ids to handle shadowed variable names. -type iterRangeScopes map[string][]int64 - -func (vs iterRangeScopes) push(varName string, expr ast.Expr) { - vs[varName] = append(vs[varName], expr.ID()) -} - -func (vs iterRangeScopes) pop(varName string) { - varStack := vs[varName] - vs[varName] = varStack[:len(varStack)-1] -} - -func (vs iterRangeScopes) peek(varName string) (int64, bool) { - varStack := vs[varName] - if len(varStack) > 0 { - return varStack[len(varStack)-1], true - } - return 0, false -} - // CostOption configures flags which affect cost computations. type CostOption func(*coster) error @@ -300,7 +257,7 @@ func PresenceTestHasCost(hasCost bool) CostOption { c.presenceTestCost = selectAndIdentCost return nil } - c.presenceTestCost = CostEstimate{Min: 0, Max: 0} + c.presenceTestCost = FixedCostEstimate(0) return nil } } @@ -325,10 +282,11 @@ func Cost(checked *ast.AST, estimator CostEstimator, opts ...CostOption) (CostEs checkedAST: checked, estimator: estimator, overloadEstimators: map[string]FunctionEstimator{}, - exprPath: map[int64][]string{}, - iterRanges: map[string][]int64{}, + exprPaths: map[int64][]string{}, + localVars: make(scopes), computedSizes: map[int64]SizeEstimate{}, - presenceTestCost: CostEstimate{Min: 1, Max: 1}, + computedEntrySizes: map[int64]entrySizeEstimate{}, + presenceTestCost: FixedCostEstimate(1), } for _, opt := range opts { err := opt(c) @@ -339,6 +297,165 @@ func Cost(checked *ast.AST, estimator CostEstimator, opts ...CostOption) (CostEs return c.cost(checked.Expr()), nil } +type coster struct { + // exprPaths maps from Expr Id to field path. + exprPaths map[int64][]string + // localVars tracks the local and iteration variables assigned during evaluation. + localVars scopes + // computedSizes tracks the computed sizes of call results. + computedSizes map[int64]SizeEstimate + // computedEntrySizes tracks the size of list and map entries + computedEntrySizes map[int64]entrySizeEstimate + + checkedAST *ast.AST + estimator CostEstimator + overloadEstimators map[string]FunctionEstimator + // presenceTestCost will either be a zero or one based on whether has() macros count against cost computations. + presenceTestCost CostEstimate +} + +// entrySizeEstimate captures the container kind and associated key/index and value SizeEstimate values. +// +// An entrySizeEstimate only exists if both the key/index and the value have SizeEstimate values, otherwise +// a nil entrySizeEstimate should be used. +type entrySizeEstimate struct { + containerKind types.Kind + key SizeEstimate + val SizeEstimate +} + +// container returns the container kind (list or map) of the entry. +func (s *entrySizeEstimate) container() types.Kind { + if s == nil { + return types.UnknownKind + } + return s.containerKind +} + +// keySize returns the SizeEstimate for the key if one exists. +func (s *entrySizeEstimate) keySize() *SizeEstimate { + if s == nil { + return nil + } + return &s.key +} + +// valSize returns the SizeEstimate for the value if one exists. +func (s *entrySizeEstimate) valSize() *SizeEstimate { + if s == nil { + return nil + } + return &s.val +} + +func (s *entrySizeEstimate) union(other *entrySizeEstimate) *entrySizeEstimate { + if s == nil || other == nil { + return nil + } + sk := s.key.Union(other.key) + sv := s.val.Union(other.val) + return &entrySizeEstimate{ + containerKind: s.containerKind, + key: sk, + val: sv, + } +} + +// localVar captures the local variable size and entrySize estimates if they exist for variables +type localVar struct { + exprID int64 + path []string + size *SizeEstimate + entrySize *entrySizeEstimate +} + +// scopes is a stack of variable name to integer id stack to handle scopes created by cel.bind() like macros +type scopes map[string][]*localVar + +func (s scopes) push(varName string, expr ast.Expr, path []string, size *SizeEstimate, entrySize *entrySizeEstimate) { + s[varName] = append(s[varName], &localVar{ + exprID: expr.ID(), + path: path, + size: size, + entrySize: entrySize, + }) +} + +func (s scopes) pop(varName string) { + varStack := s[varName] + s[varName] = varStack[:len(varStack)-1] +} + +func (s scopes) peek(varName string) (*localVar, bool) { + varStack := s[varName] + if len(varStack) > 0 { + return varStack[len(varStack)-1], true + } + return nil, false +} + +func (c *coster) pushIterKey(varName string, rangeExpr ast.Expr) { + entrySize := c.computeEntrySize(rangeExpr) + size := entrySize.keySize() + path := c.getPath(rangeExpr) + container := entrySize.container() + if container == types.UnknownKind { + container = c.getType(rangeExpr).Kind() + } + subpath := "@keys" + if container == types.ListKind { + subpath = "@indices" + } + c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) +} + +func (c *coster) pushIterValue(varName string, rangeExpr ast.Expr) { + entrySize := c.computeEntrySize(rangeExpr) + size := entrySize.valSize() + path := c.getPath(rangeExpr) + container := entrySize.container() + if container == types.UnknownKind { + container = c.getType(rangeExpr).Kind() + } + subpath := "@values" + if container == types.ListKind { + subpath = "@items" + } + c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) +} + +func (c *coster) pushIterSingle(varName string, rangeExpr ast.Expr) { + entrySize := c.computeEntrySize(rangeExpr) + size := entrySize.keySize() + subpath := "@keys" + container := entrySize.container() + if container == types.UnknownKind { + container = c.getType(rangeExpr).Kind() + } + if container == types.ListKind { + size = entrySize.valSize() + subpath = "@items" + } + path := c.getPath(rangeExpr) + c.localVars.push(varName, rangeExpr, append(path, subpath), size, nil) +} + +func (c *coster) pushLocalVar(varName string, e ast.Expr) { + path := c.getPath(e) + // note: retrieve the entry size for the local variable based on the size of the binding expression + // since the binding expression could be a list or map, the entry size should also be propagated + entrySize := c.computeEntrySize(e) + c.localVars.push(varName, e, path, c.computeSize(e), entrySize) +} + +func (c *coster) peekLocalVar(varName string) (*localVar, bool) { + return c.localVars.peek(varName) +} + +func (c *coster) popLocalVar(varName string) { + c.localVars.pop(varName) +} + func (c *coster) cost(e ast.Expr) CostEstimate { if e == nil { return CostEstimate{} @@ -360,7 +477,11 @@ func (c *coster) cost(e ast.Expr) CostEstimate { case ast.StructKind: cost = c.costCreateStruct(e) case ast.ComprehensionKind: - cost = c.costComprehension(e) + if c.isBind(e) { + cost = c.costBind(e) + } else { + cost = c.costComprehension(e) + } default: return CostEstimate{} } @@ -370,17 +491,11 @@ func (c *coster) cost(e ast.Expr) CostEstimate { func (c *coster) costIdent(e ast.Expr) CostEstimate { identName := e.AsIdent() // build and track the field path - if iterRange, ok := c.iterRanges.peek(identName); ok { - switch c.checkedAST.GetType(iterRange).Kind() { - case types.ListKind: - c.addPath(e, append(c.exprPath[iterRange], "@items")) - case types.MapKind: - c.addPath(e, append(c.exprPath[iterRange], "@keys")) - } + if v, ok := c.peekLocalVar(identName); ok { + c.addPath(e, v.path) } else { c.addPath(e, []string{identName}) } - return selectAndIdentCost } @@ -405,14 +520,18 @@ func (c *coster) costSelect(e ast.Expr) CostEstimate { // build and track the field path c.addPath(e, append(c.getPath(sel.Operand()), sel.FieldName())) - return sum } func (c *coster) costCall(e ast.Expr) CostEstimate { + // Dyn is just a way to disable type-checking, so return the cost of 1 with the cost of the argument + if dynEstimate := c.maybeUnwrapDynCall(e); dynEstimate != nil { + return *dynEstimate + } + + // Continue estimating the cost of all other calls. call := e.AsCall() args := call.Args() - var sum CostEstimate argTypes := make([]AstNode, len(args)) @@ -435,7 +554,7 @@ func (c *coster) costCall(e ast.Expr) CostEstimate { fnCost := CostEstimate{Min: uint64(math.MaxUint64), Max: 0} var resultSize *SizeEstimate for _, overload := range overloadIDs { - overloadCost := c.functionCost(call.FunctionName(), overload, &targetType, argTypes, argCosts) + overloadCost := c.functionCost(e, call.FunctionName(), overload, &targetType, argTypes, argCosts) fnCost = fnCost.Union(overloadCost.CostEstimate) if overloadCost.ResultSize != nil { if resultSize == nil { @@ -449,37 +568,73 @@ func (c *coster) costCall(e ast.Expr) CostEstimate { switch overload { case overloads.IndexList: if len(args) > 0 { + // note: assigning resultSize here could be redundant with the path-based lookup later + resultSize = c.computeEntrySize(args[0]).valSize() c.addPath(e, append(c.getPath(args[0]), "@items")) } case overloads.IndexMap: if len(args) > 0 { + resultSize = c.computeEntrySize(args[0]).valSize() c.addPath(e, append(c.getPath(args[0]), "@values")) } } + if resultSize == nil { + resultSize = c.computeSize(e) + } } - if resultSize != nil { - c.computedSizes[e.ID()] = *resultSize - } + c.setSize(e, resultSize) return sum.Add(fnCost) } +func (c *coster) maybeUnwrapDynCall(e ast.Expr) *CostEstimate { + call := e.AsCall() + if call.FunctionName() != "dyn" { + return nil + } + arg := call.Args()[0] + argCost := c.cost(arg) + c.copySizeEstimates(e, arg) + callCost := FixedCostEstimate(1).Add(argCost) + return &callCost +} + func (c *coster) costCreateList(e ast.Expr) CostEstimate { create := e.AsList() var sum CostEstimate + itemSize := SizeEstimate{Min: math.MaxUint64, Max: 0} + if create.Size() == 0 { + itemSize.Min = 0 + } for _, e := range create.Elements() { sum = sum.Add(c.cost(e)) + is := c.sizeOrUnknown(e) + itemSize = itemSize.Union(is) } + c.setEntrySize(e, &entrySizeEstimate{containerKind: types.ListKind, key: FixedSizeEstimate(1), val: itemSize}) return sum.Add(createListBaseCost) } func (c *coster) costCreateMap(e ast.Expr) CostEstimate { mapVal := e.AsMap() var sum CostEstimate + keySize := SizeEstimate{Min: math.MaxUint64, Max: 0} + valSize := SizeEstimate{Min: math.MaxUint64, Max: 0} + if mapVal.Size() == 0 { + valSize.Min = 0 + keySize.Min = 0 + } for _, ent := range mapVal.Entries() { entry := ent.AsMapEntry() sum = sum.Add(c.cost(entry.Key())) sum = sum.Add(c.cost(entry.Value())) + // Compute the key size range + ks := c.sizeOrUnknown(entry.Key()) + keySize = keySize.Union(ks) + // Compute the value size range + vs := c.sizeOrUnknown(entry.Value()) + valSize = valSize.Union(vs) } + c.setEntrySize(e, &entrySizeEstimate{containerKind: types.MapKind, key: keySize, val: valSize}) return sum.Add(createMapBaseCost) } @@ -498,43 +653,76 @@ func (c *coster) costComprehension(e ast.Expr) CostEstimate { var sum CostEstimate sum = sum.Add(c.cost(comp.IterRange())) sum = sum.Add(c.cost(comp.AccuInit())) + c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) - // Track the iterRange of each IterVar for field path construction - c.iterRanges.push(comp.IterVar(), comp.IterRange()) + // Track the iterRange of each IterVar and AccuVar for field path construction + if comp.HasIterVar2() { + c.pushIterKey(comp.IterVar(), comp.IterRange()) + c.pushIterValue(comp.IterVar2(), comp.IterRange()) + } else { + c.pushIterSingle(comp.IterVar(), comp.IterRange()) + } + + // Determine the cost for each element in the loop loopCost := c.cost(comp.LoopCondition()) stepCost := c.cost(comp.LoopStep()) - c.iterRanges.pop(comp.IterVar()) + + // Clear the intermediate variable tracking. + c.popLocalVar(comp.IterVar()) + if comp.HasIterVar2() { + c.popLocalVar(comp.IterVar2()) + } + + // Determine the result cost. sum = sum.Add(c.cost(comp.Result())) - rangeCnt := c.sizeEstimate(c.newAstNode(comp.IterRange())) - - c.computedSizes[e.ID()] = rangeCnt + c.localVars.pop(comp.AccuVar()) + // Estimate the cost of the loop. + rangeCnt := c.sizeOrUnknown(comp.IterRange()) rangeCost := rangeCnt.MultiplyByCost(stepCost.Add(loopCost)) sum = sum.Add(rangeCost) + switch k := comp.AccuInit().Kind(); k { + case ast.LiteralKind: + c.setSize(e, c.computeSize(comp.AccuInit())) + case ast.ListKind, ast.MapKind: + c.setSize(e, &rangeCnt) + // For a step which produces a container value, it will have an entry size associated + // with its expression id. + if stepEntrySize := c.computeEntrySize(comp.LoopStep()); stepEntrySize != nil { + c.setEntrySize(e, stepEntrySize) + break + } + } return sum } -func (c *coster) sizeEstimate(t AstNode) SizeEstimate { - if l := t.ComputedSize(); l != nil { - return *l - } - if l := c.estimator.EstimateSize(t); l != nil { - return *l - } - // return an estimate of 1 for return types of set - // lengths, since strings/bytes/more complex objects could be of - // variable length - if isScalar(t.Type()) { - // TODO: since the logic for size estimation is split between - // ComputedSize and isScalar, changing one will likely require changing - // the other, so they should be merged in the future if possible - return SizeEstimate{Min: 1, Max: 1} - } - return SizeEstimate{Min: 0, Max: math.MaxUint64} +func (c *coster) isBind(e ast.Expr) bool { + comp := e.AsComprehension() + iterRange := comp.IterRange() + loopCond := comp.LoopCondition() + return iterRange.Kind() == ast.ListKind && iterRange.AsList().Size() == 0 && + loopCond.Kind() == ast.LiteralKind && loopCond.AsLiteral() == types.False && + comp.AccuVar() != parser.AccumulatorName } -func (c *coster) functionCost(function, overloadID string, target *AstNode, args []AstNode, argCosts []CostEstimate) CallEstimate { +func (c *coster) costBind(e ast.Expr) CostEstimate { + comp := e.AsComprehension() + var sum CostEstimate + // Binds are lazily initialized, so we retain the cost of an empty iteration range. + sum = sum.Add(c.cost(comp.IterRange())) + sum = sum.Add(c.cost(comp.AccuInit())) + + c.pushLocalVar(comp.AccuVar(), comp.AccuInit()) + sum = sum.Add(c.cost(comp.Result())) + c.popLocalVar(comp.AccuVar()) + + // Associate the bind output size with the result size. + c.copySizeEstimates(e, comp.Result()) + return sum +} + +func (c *coster) functionCost(e ast.Expr, function, overloadID string, target *AstNode, args []AstNode, argCosts []CostEstimate) CallEstimate { argCostSum := func() CostEstimate { var sum CostEstimate for _, a := range argCosts { @@ -559,35 +747,42 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args case overloads.ExtFormatString: if target != nil { // ResultSize not calculated because we can't bound the max size. - return CallEstimate{CostEstimate: c.sizeEstimate(*target).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} + return CallEstimate{ + CostEstimate: c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} } case overloads.StringToBytes: if len(args) == 1 { - sz := c.sizeEstimate(args[0]) + sz := c.sizeOrUnknown(args[0]) // ResultSize max is when each char converts to 4 bytes. - return CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &SizeEstimate{Min: sz.Min, Max: sz.Max * 4}} + return CallEstimate{ + CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), + ResultSize: &SizeEstimate{Min: sz.Min, Max: sz.Max * 4}} } case overloads.BytesToString: if len(args) == 1 { - sz := c.sizeEstimate(args[0]) + sz := c.sizeOrUnknown(args[0]) // ResultSize min is when 4 bytes convert to 1 char. - return CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &SizeEstimate{Min: sz.Min / 4, Max: sz.Max}} + return CallEstimate{ + CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), + ResultSize: &SizeEstimate{Min: sz.Min / 4, Max: sz.Max}} } case overloads.ExtQuoteString: if len(args) == 1 { - sz := c.sizeEstimate(args[0]) + sz := c.sizeOrUnknown(args[0]) // ResultSize max is when each char is escaped. 2 quote chars always added. - return CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &SizeEstimate{Min: sz.Min + 2, Max: sz.Max*2 + 2}} + return CallEstimate{ + CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), + ResultSize: &SizeEstimate{Min: sz.Min + 2, Max: sz.Max*2 + 2}} } case overloads.StartsWithString, overloads.EndsWithString: if len(args) == 1 { - return CallEstimate{CostEstimate: c.sizeEstimate(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} + return CallEstimate{CostEstimate: c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} } case overloads.InList: // If a list is composed entirely of constant values this is O(1), but we don't account for that here. // We just assume all list containment checks are O(n). if len(args) == 2 { - return CallEstimate{CostEstimate: c.sizeEstimate(args[1]).MultiplyByCostFactor(1).Add(argCostSum())} + return CallEstimate{CostEstimate: c.sizeOrUnknown(args[1]).MultiplyByCostFactor(1).Add(argCostSum())} } // O(nm) functions case overloads.MatchesString: @@ -595,19 +790,19 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args if target != nil && len(args) == 1 { // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0 // in case where string is empty but regex is still expensive. - strCost := c.sizeEstimate(*target).Add(SizeEstimate{Min: 1, Max: 1}).MultiplyByCostFactor(common.StringTraversalCostFactor) + strCost := c.sizeOrUnknown(*target).Add(SizeEstimate{Min: 1, Max: 1}).MultiplyByCostFactor(common.StringTraversalCostFactor) // We don't know how many expressions are in the regex, just the string length (a huge // improvement here would be to somehow get a count the number of expressions in the regex or // how many states are in the regex state machine and use that to measure regex cost). // For now, we're making a guess that each expression in a regex is typically at least 4 chars // in length. - regexCost := c.sizeEstimate(args[0]).MultiplyByCostFactor(common.RegexStringLengthCostFactor) + regexCost := c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.RegexStringLengthCostFactor) return CallEstimate{CostEstimate: strCost.Multiply(regexCost).Add(argCostSum())} } case overloads.ContainsString: if target != nil && len(args) == 1 { - strCost := c.sizeEstimate(*target).MultiplyByCostFactor(common.StringTraversalCostFactor) - substrCost := c.sizeEstimate(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor) + strCost := c.sizeOrUnknown(*target).MultiplyByCostFactor(common.StringTraversalCostFactor) + substrCost := c.sizeOrUnknown(args[0]).MultiplyByCostFactor(common.StringTraversalCostFactor) return CallEstimate{CostEstimate: strCost.Multiply(substrCost).Add(argCostSum())} } case overloads.LogicalOr, overloads.LogicalAnd: @@ -617,7 +812,9 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args argCost := CostEstimate{Min: lhs.Min, Max: lhs.Add(rhs).Max} return CallEstimate{CostEstimate: argCost} case overloads.Conditional: - size := c.sizeEstimate(args[1]).Union(c.sizeEstimate(args[2])) + size := c.sizeOrUnknown(args[1]).Union(c.sizeOrUnknown(args[2])) + resultEntrySize := c.computeEntrySize(args[1].Expr()).union(c.computeEntrySize(args[2].Expr())) + c.setEntrySize(e, resultEntrySize) conditionalCost := argCosts[0] ifTrueCost := argCosts[1] ifFalseCost := argCosts[2] @@ -625,13 +822,19 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args return CallEstimate{CostEstimate: argCost, ResultSize: &size} case overloads.AddString, overloads.AddBytes, overloads.AddList: if len(args) == 2 { - lhsSize := c.sizeEstimate(args[0]) - rhsSize := c.sizeEstimate(args[1]) + lhsSize := c.sizeOrUnknown(args[0]) + rhsSize := c.sizeOrUnknown(args[1]) resultSize := lhsSize.Add(rhsSize) + rhsEntrySize := c.computeEntrySize(args[0].Expr()) + lhsEntrySize := c.computeEntrySize(args[1].Expr()) + resultEntrySize := rhsEntrySize.union(lhsEntrySize) + if resultEntrySize != nil { + c.setEntrySize(e, resultEntrySize) + } switch overloadID { case overloads.AddList: // list concatenation is O(1), but we handle it here to track size - return CallEstimate{CostEstimate: CostEstimate{Min: 1, Max: 1}.Add(argCostSum()), ResultSize: &resultSize} + return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum()), ResultSize: &resultSize} default: return CallEstimate{CostEstimate: resultSize.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), ResultSize: &resultSize} } @@ -639,8 +842,8 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString, overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes, overloads.Equals, overloads.NotEquals: - lhsCost := c.sizeEstimate(args[0]) - rhsCost := c.sizeEstimate(args[1]) + lhsCost := c.sizeOrUnknown(args[0]) + rhsCost := c.sizeOrUnknown(args[1]) min := uint64(0) smallestMax := lhsCost.Max if rhsCost.Max < smallestMax { @@ -650,14 +853,16 @@ func (c *coster) functionCost(function, overloadID string, target *AstNode, args min = 1 } // equality of 2 scalar values results in a cost of 1 - return CallEstimate{CostEstimate: CostEstimate{Min: min, Max: smallestMax}.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum())} + return CallEstimate{ + CostEstimate: CostEstimate{Min: min, Max: smallestMax}.MultiplyByCostFactor(common.StringTraversalCostFactor).Add(argCostSum()), + } } // O(1) functions // See CostTracker.costCall for more details about O(1) cost calculations // Benchmarks suggest that most of the other operations take +/- 50% of a base cost unit // which on an Intel xeon 2.20GHz CPU is 50ns. - return CallEstimate{CostEstimate: CostEstimate{Min: 1, Max: 1}.Add(argCostSum())} + return CallEstimate{CostEstimate: FixedCostEstimate(1).Add(argCostSum())} } func (c *coster) getType(e ast.Expr) *types.Type { @@ -665,28 +870,145 @@ func (c *coster) getType(e ast.Expr) *types.Type { } func (c *coster) getPath(e ast.Expr) []string { - return c.exprPath[e.ID()] + if e.Kind() == ast.IdentKind { + if v, found := c.peekLocalVar(e.AsIdent()); found { + return v.path[:] + } + } + return c.exprPaths[e.ID()][:] } func (c *coster) addPath(e ast.Expr, path []string) { - c.exprPath[e.ID()] = path + c.exprPaths[e.ID()] = path +} + +func isAccumulatorVar(name string) bool { + return name == parser.AccumulatorName || name == parser.HiddenAccumulatorName } func (c *coster) newAstNode(e ast.Expr) *astNode { path := c.getPath(e) - if len(path) > 0 && path[0] == parser.AccumulatorName { + if len(path) > 0 && isAccumulatorVar(path[0]) { // only provide paths to root vars; omit accumulator vars path = nil } - var derivedSize *SizeEstimate - if size, ok := c.computedSizes[e.ID()]; ok { - derivedSize = &size - } return &astNode{ path: path, t: c.getType(e), expr: e, - derivedSize: derivedSize} + derivedSize: c.computeSize(e)} +} + +func (c *coster) setSize(e ast.Expr, size *SizeEstimate) { + if size == nil { + return + } + // Store the computed size with the expression + c.computedSizes[e.ID()] = *size +} + +func (c *coster) sizeOrUnknown(node any) SizeEstimate { + switch v := node.(type) { + case ast.Expr: + if sz := c.computeSize(v); sz != nil { + return *sz + } + case AstNode: + if sz := v.ComputedSize(); sz != nil { + return *sz + } + } + return UnknownSizeEstimate() +} + +func (c *coster) copySizeEstimates(dst, src ast.Expr) { + c.setSize(dst, c.computeSize(src)) + c.setEntrySize(dst, c.computeEntrySize(src)) +} + +func (c *coster) computeSize(e ast.Expr) *SizeEstimate { + if size, ok := c.computedSizes[e.ID()]; ok { + return &size + } + if size := computeExprSize(e); size != nil { + return size + } + // Ensure size estimates are computed first as users may choose to override the costs that + // CEL would otherwise ascribe to the type. + node := astNode{expr: e, path: c.getPath(e), t: c.getType(e)} + if size := c.estimator.EstimateSize(node); size != nil { + // storing the computed size should reduce calls to EstimateSize() + c.computedSizes[e.ID()] = *size + return size + } + if size := computeTypeSize(c.getType(e)); size != nil { + return size + } + if e.Kind() == ast.IdentKind { + varName := e.AsIdent() + if v, ok := c.peekLocalVar(varName); ok && v.size != nil { + return v.size + } + } + return nil +} + +func (c *coster) setEntrySize(e ast.Expr, size *entrySizeEstimate) { + if size == nil { + return + } + c.computedEntrySizes[e.ID()] = *size +} + +func (c *coster) computeEntrySize(e ast.Expr) *entrySizeEstimate { + if sz, found := c.computedEntrySizes[e.ID()]; found { + return &sz + } + if e.Kind() == ast.IdentKind { + varName := e.AsIdent() + if v, ok := c.peekLocalVar(varName); ok && v.entrySize != nil { + return v.entrySize + } + } + return nil +} + +func computeExprSize(expr ast.Expr) *SizeEstimate { + var v uint64 + switch expr.Kind() { + case ast.LiteralKind: + switch ck := expr.AsLiteral().(type) { + case types.String: + // converting to runes here is an O(n) operation, but + // this is consistent with how size is computed at runtime, + // and how the language definition defines string size + v = uint64(len([]rune(ck))) + case types.Bytes: + v = uint64(len(ck)) + case types.Bool, types.Double, types.Duration, + types.Int, types.Timestamp, types.Uint, + types.Null: + v = uint64(1) + default: + return nil + } + case ast.ListKind: + v = uint64(expr.AsList().Size()) + case ast.MapKind: + v = uint64(expr.AsMap().Size()) + default: + return nil + } + cost := FixedSizeEstimate(v) + return &cost +} + +func computeTypeSize(t *types.Type) *SizeEstimate { + if isScalar(t) { + cost := FixedSizeEstimate(1) + return &cost + } + return nil } // isScalar returns true if the given type is known to be of a constant size at @@ -696,10 +1018,24 @@ func isScalar(t *types.Type) bool { switch t.Kind() { case types.BoolKind, types.DoubleKind, types.DurationKind, types.IntKind, types.TimestampKind, types.UintKind: return true + case types.OpaqueKind: + if t.TypeName() == "optional_type" { + return isScalar(t.Parameters()[0]) + } } return false } var ( doubleTwoTo64 = math.Ldexp(1.0, 64) + + unknownSizeEstimate = SizeEstimate{Min: 0, Max: math.MaxUint64} + unknownCostEstimate = unknownSizeEstimate.MultiplyByCostFactor(1) + + selectAndIdentCost = FixedCostEstimate(common.SelectAndIdentCost) + constCost = FixedCostEstimate(common.ConstCost) + + createListBaseCost = FixedCostEstimate(common.ListCreateBaseCost) + createMapBaseCost = FixedCostEstimate(common.MapCreateBaseCost) + createMessageBaseCost = FixedCostEstimate(common.StructCreateBaseCost) ) diff --git a/e2e/vendor/github.com/google/cel-go/common/ast/factory.go b/e2e/vendor/github.com/google/cel-go/common/ast/factory.go index 994806b79..d4dcde4d9 100644 --- a/e2e/vendor/github.com/google/cel-go/common/ast/factory.go +++ b/e2e/vendor/github.com/google/cel-go/common/ast/factory.go @@ -40,15 +40,18 @@ type ExprFactory interface { NewIdent(id int64, name string) Expr // NewAccuIdent creates an Expr value representing an accumulator identifier within a - //comprehension. + // comprehension. NewAccuIdent(id int64) Expr + // AccuIdentName reports the name of the accumulator variable to be used within a comprehension. + AccuIdentName() string + // NewLiteral creates an Expr value representing a literal value, such as a string or integer. NewLiteral(id int64, value ref.Val) Expr // NewList creates an Expr value representing a list literal expression with optional indices. // - // Optional indicies will typically be empty unless the CEL optional types are enabled. + // Optional indices will typically be empty unless the CEL optional types are enabled. NewList(id int64, elems []Expr, optIndices []int32) Expr // NewMap creates an Expr value representing a map literal expression @@ -78,11 +81,23 @@ type ExprFactory interface { isExprFactory() } -type baseExprFactory struct{} +type baseExprFactory struct { + accumulatorName string +} // NewExprFactory creates an ExprFactory instance. func NewExprFactory() ExprFactory { - return &baseExprFactory{} + return &baseExprFactory{ + "@result", + } +} + +// NewExprFactoryWithAccumulator creates an ExprFactory instance with a custom +// accumulator identifier name. +func NewExprFactoryWithAccumulator(id string) ExprFactory { + return &baseExprFactory{ + id, + } } func (fac *baseExprFactory) NewCall(id int64, function string, args ...Expr) Expr { @@ -138,7 +153,11 @@ func (fac *baseExprFactory) NewIdent(id int64, name string) Expr { } func (fac *baseExprFactory) NewAccuIdent(id int64) Expr { - return fac.NewIdent(id, "__result__") + return fac.NewIdent(id, fac.AccuIdentName()) +} + +func (fac *baseExprFactory) AccuIdentName() string { + return fac.accumulatorName } func (fac *baseExprFactory) NewLiteral(id int64, value ref.Val) Expr { diff --git a/e2e/vendor/github.com/google/cel-go/common/debug/debug.go b/e2e/vendor/github.com/google/cel-go/common/debug/debug.go index 25d2e3d71..75f5f0d63 100644 --- a/e2e/vendor/github.com/google/cel-go/common/debug/debug.go +++ b/e2e/vendor/github.com/google/cel-go/common/debug/debug.go @@ -257,7 +257,7 @@ func formatLiteral(c ref.Val) string { case types.Bool: return fmt.Sprintf("%t", v) case types.Bytes: - return fmt.Sprintf("b\"%s\"", string(v)) + return fmt.Sprintf("b%s", strconv.Quote(string(v))) case types.Double: return fmt.Sprintf("%v", float64(v)) case types.Int: diff --git a/e2e/vendor/github.com/google/cel-go/common/decls/decls.go b/e2e/vendor/github.com/google/cel-go/common/decls/decls.go index f67808feb..bfeb52c51 100644 --- a/e2e/vendor/github.com/google/cel-go/common/decls/decls.go +++ b/e2e/vendor/github.com/google/cel-go/common/decls/decls.go @@ -782,6 +782,11 @@ func TypeVariable(t *types.Type) *VariableDecl { return NewVariable(t.TypeName(), types.NewTypeTypeWithParam(t)) } +// VariableDeclToExprDecl converts a go-native variable declaration into a protobuf-type variable declaration. +func VariableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { + return variableDeclToExprDecl(v) +} + // variableDeclToExprDecl converts a go-native variable declaration into a protobuf-type variable declaration. func variableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { varType, err := types.TypeToExprType(v.Type()) @@ -791,6 +796,11 @@ func variableDeclToExprDecl(v *VariableDecl) (*exprpb.Decl, error) { return chkdecls.NewVar(v.Name(), varType), nil } +// FunctionDeclToExprDecl converts a go-native function declaration into a protobuf-typed function declaration. +func FunctionDeclToExprDecl(f *FunctionDecl) (*exprpb.Decl, error) { + return functionDeclToExprDecl(f) +} + // functionDeclToExprDecl converts a go-native function declaration into a protobuf-typed function declaration. func functionDeclToExprDecl(f *FunctionDecl) (*exprpb.Decl, error) { overloads := make([]*exprpb.Decl_FunctionDecl_Overload, len(f.overloads)) diff --git a/e2e/vendor/github.com/google/cel-go/common/errors.go b/e2e/vendor/github.com/google/cel-go/common/errors.go index 25adc73d8..c8865df8c 100644 --- a/e2e/vendor/github.com/google/cel-go/common/errors.go +++ b/e2e/vendor/github.com/google/cel-go/common/errors.go @@ -30,9 +30,13 @@ type Errors struct { // NewErrors creates a new instance of the Errors type. func NewErrors(source Source) *Errors { + src := source + if src == nil { + src = NewTextSource("") + } return &Errors{ errors: []*Error{}, - source: source, + source: src, maxErrorsToReport: 100, } } @@ -42,6 +46,11 @@ func (e *Errors) ReportError(l Location, format string, args ...any) { e.ReportErrorAtID(0, l, format, args...) } +// ReportErrorString records an error at a source location. +func (e *Errors) ReportErrorString(l Location, message string) { + e.ReportErrorAtID(0, l, "%s", message) +} + // ReportErrorAtID records an error at a source location and expression id. func (e *Errors) ReportErrorAtID(id int64, l Location, format string, args ...any) { e.numErrors++ diff --git a/e2e/vendor/github.com/google/cel-go/common/types/err.go b/e2e/vendor/github.com/google/cel-go/common/types/err.go index 9c9d9e21e..17ab1a95e 100644 --- a/e2e/vendor/github.com/google/cel-go/common/types/err.go +++ b/e2e/vendor/github.com/google/cel-go/common/types/err.go @@ -62,6 +62,12 @@ func NewErr(format string, args ...any) ref.Val { return &Err{error: fmt.Errorf(format, args...)} } +// NewErrFromString creates a new Err with the provided message. +// TODO: Audit the use of this function and standardize the error messages and codes. +func NewErrFromString(message string) ref.Val { + return &Err{error: errors.New(message)} +} + // NewErrWithNodeID creates a new Err described by the format string and args. // TODO: Audit the use of this function and standardize the error messages and codes. func NewErrWithNodeID(id int64, format string, args ...any) ref.Val { diff --git a/e2e/vendor/github.com/google/cel-go/common/types/list.go b/e2e/vendor/github.com/google/cel-go/common/types/list.go index ca47d39fe..7e68a5daf 100644 --- a/e2e/vendor/github.com/google/cel-go/common/types/list.go +++ b/e2e/vendor/github.com/google/cel-go/common/types/list.go @@ -243,7 +243,7 @@ func (l *baseList) Equal(other ref.Val) ref.Val { func (l *baseList) Get(index ref.Val) ref.Val { ind, err := IndexOrError(index) if err != nil { - return ValOrErr(index, err.Error()) + return ValOrErr(index, "%v", err) } if ind < 0 || ind >= l.size { return NewErr("index '%d' out of range in list size '%d'", ind, l.Size()) @@ -427,7 +427,7 @@ func (l *concatList) Equal(other ref.Val) ref.Val { func (l *concatList) Get(index ref.Val) ref.Val { ind, err := IndexOrError(index) if err != nil { - return ValOrErr(index, err.Error()) + return ValOrErr(index, "%v", err) } i := Int(ind) if i < l.prevList.Size().(Int) { diff --git a/e2e/vendor/github.com/google/cel-go/common/types/object.go b/e2e/vendor/github.com/google/cel-go/common/types/object.go index 8ba0af9fb..5377bff8d 100644 --- a/e2e/vendor/github.com/google/cel-go/common/types/object.go +++ b/e2e/vendor/github.com/google/cel-go/common/types/object.go @@ -151,7 +151,7 @@ func (o *protoObj) Get(index ref.Val) ref.Val { } fv, err := fd.GetFrom(o.value) if err != nil { - return NewErr(err.Error()) + return NewErrFromString(err.Error()) } return o.NativeToValue(fv) } diff --git a/e2e/vendor/github.com/google/cel-go/common/types/types.go b/e2e/vendor/github.com/google/cel-go/common/types/types.go index 1c5b6c40c..f419beabd 100644 --- a/e2e/vendor/github.com/google/cel-go/common/types/types.go +++ b/e2e/vendor/github.com/google/cel-go/common/types/types.go @@ -768,6 +768,19 @@ func ProtoAsType(t *celpb.Type) (*Type, error) { } } +// TypeToProto converts from a CEL-native type representation to canonical CEL celpb.Type protobuf type. +func TypeToProto(t *Type) (*celpb.Type, error) { + exprType, err := TypeToExprType(t) + if err != nil { + return nil, err + } + var pbtype celpb.Type + if err = convertProto(exprType, &pbtype); err != nil { + return nil, err + } + return &pbtype, nil +} + func maybeWrapper(t *Type, pbType *exprpb.Type) *exprpb.Type { if t.IsAssignableType(NullType) { return chkdecls.NewWrapperType(pbType) diff --git a/e2e/vendor/github.com/google/cel-go/ext/BUILD.bazel b/e2e/vendor/github.com/google/cel-go/ext/BUILD.bazel index 1fece7006..b764fa1f5 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/BUILD.bazel +++ b/e2e/vendor/github.com/google/cel-go/ext/BUILD.bazel @@ -8,6 +8,7 @@ go_library( name = "go_default_library", srcs = [ "bindings.go", + "comprehensions.go", "encoders.go", "formatting.go", "guards.go", @@ -45,7 +46,9 @@ go_test( name = "go_default_test", size = "small", srcs = [ - "encoders_test.go", + "bindings_test.go", + "comprehensions_test.go", + "encoders_test.go", "lists_test.go", "math_test.go", "native_test.go", diff --git a/e2e/vendor/github.com/google/cel-go/ext/README.md b/e2e/vendor/github.com/google/cel-go/ext/README.md index 07e544d0d..4620204fc 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/README.md +++ b/e2e/vendor/github.com/google/cel-go/ext/README.md @@ -11,7 +11,7 @@ in expressions. ### Cel.Bind Binds a simple identifier to an initialization expression which may be used -in a subsequenct result expression. Bindings may also be nested within each +in a subsequent result expression. Bindings may also be nested within each other. cel.bind(, , ) @@ -29,7 +29,7 @@ Local bindings are not guaranteed to be evaluated before use. ## Encoders -Encoding utilies for marshalling data into standardized representations. +Encoding utilities for marshalling data into standardized representations. ### Base64.Decode @@ -500,6 +500,36 @@ Examples: ].sortBy(e, e.score).map(e, e.name) == ["bar", "foo", "baz"] +### Last + +**Introduced in the OptionalTypes library version 2** + +Returns an optional with the last value from the list or `optional.None` if the +list is empty. + + .last() -> + +Examples: + + [1, 2, 3].last().value() == 3 + [].last().orValue('test') == 'test' + +This is syntactic sugar for list[list.size()-1]. + +### First + +**Introduced in the OptionalTypes library version 2** + +Returns an optional with the first value from the list or `optional.None` if the +list is empty. + + .first() -> + +Examples: + + [1, 2, 3].first().value() == 1 + [].first().orValue('test') == 'test' + ## Sets Sets provides set relationship tests. diff --git a/e2e/vendor/github.com/google/cel-go/ext/comprehensions.go b/e2e/vendor/github.com/google/cel-go/ext/comprehensions.go index 1428558d8..f08d8f9da 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/comprehensions.go +++ b/e2e/vendor/github.com/google/cel-go/ext/comprehensions.go @@ -16,6 +16,7 @@ package ext import ( "fmt" + "math" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/ast" @@ -159,19 +160,36 @@ const ( // // {'greeting': 'aloha', 'farewell': 'aloha'} // .transformMapEntry(keyVar, valueVar, {valueVar: keyVar}) // error, duplicate key -func TwoVarComprehensions() cel.EnvOption { - return cel.Lib(compreV2Lib{}) +func TwoVarComprehensions(options ...TwoVarComprehensionsOption) cel.EnvOption { + l := &compreV2Lib{version: math.MaxUint32} + for _, o := range options { + l = o(l) + } + return cel.Lib(l) } -type compreV2Lib struct{} +// TwoVarComprehensionsOption declares a functional operator for configuring two-variable comprehensions. +type TwoVarComprehensionsOption func(*compreV2Lib) *compreV2Lib + +// TwoVarComprehensionsVersion sets the library version for two-variable comprehensions. +func TwoVarComprehensionsVersion(version uint32) TwoVarComprehensionsOption { + return func(lib *compreV2Lib) *compreV2Lib { + lib.version = version + return lib + } +} + +type compreV2Lib struct { + version uint32 +} // LibraryName implements that SingletonLibrary interface method. -func (compreV2Lib) LibraryName() string { +func (*compreV2Lib) LibraryName() string { return "cel.lib.ext.comprev2" } // CompileOptions implements the cel.Library interface method. -func (compreV2Lib) CompileOptions() []cel.EnvOption { +func (*compreV2Lib) CompileOptions() []cel.EnvOption { kType := cel.TypeParamType("K") vType := cel.TypeParamType("V") mapKVType := cel.MapType(kType, vType) @@ -217,7 +235,7 @@ func (compreV2Lib) CompileOptions() []cel.EnvOption { } // ProgramOptions implements the cel.Library interface method -func (compreV2Lib) ProgramOptions() []cel.ProgramOption { +func (*compreV2Lib) ProgramOptions() []cel.ProgramOption { return []cel.ProgramOption{} } @@ -231,7 +249,7 @@ func quantifierAll(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) ( target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewLiteral(types.True), /*condition=*/ mef.NewCall(operators.NotStrictlyFalse, mef.NewAccuIdent()), /*step=*/ mef.NewCall(operators.LogicalAnd, mef.NewAccuIdent(), args[2]), @@ -249,7 +267,7 @@ func quantifierExists(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewLiteral(types.False), /*condition=*/ mef.NewCall(operators.NotStrictlyFalse, mef.NewCall(operators.LogicalNot, mef.NewAccuIdent())), /*step=*/ mef.NewCall(operators.LogicalOr, mef.NewAccuIdent(), args[2]), @@ -267,7 +285,7 @@ func quantifierExistsOne(mef cel.MacroExprFactory, target ast.Expr, args []ast.E target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewLiteral(types.Int(0)), /*condition=*/ mef.NewLiteral(types.True), /*step=*/ mef.NewCall(operators.Conditional, args[2], @@ -293,10 +311,10 @@ func transformList(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) ( transform = args[2] } - // __result__ = __result__ + [transform] + // accumulator = accumulator + [transform] step := mef.NewCall(operators.Add, mef.NewAccuIdent(), mef.NewList(transform)) if filter != nil { - // __result__ = (filter) ? __result__ + [transform] : __result__ + // accumulator = (filter) ? accumulator + [transform] : accumulator step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) } @@ -304,7 +322,7 @@ func transformList(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) ( target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewList(), /*condition=*/ mef.NewLiteral(types.True), step, @@ -328,17 +346,17 @@ func transformMap(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (a transform = args[2] } - // __result__ = cel.@mapInsert(__result__, iterVar1, transform) + // accumulator = cel.@mapInsert(accumulator, iterVar1, transform) step := mef.NewCall(mapInsert, mef.NewAccuIdent(), mef.NewIdent(iterVar1), transform) if filter != nil { - // __result__ = (filter) ? cel.@mapInsert(__result__, iterVar1, transform) : __result__ + // accumulator = (filter) ? cel.@mapInsert(accumulator, iterVar1, transform) : accumulator step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) } return mef.NewComprehensionTwoVar( target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewMap(), /*condition=*/ mef.NewLiteral(types.True), step, @@ -362,17 +380,17 @@ func transformMapEntry(mef cel.MacroExprFactory, target ast.Expr, args []ast.Exp transform = args[2] } - // __result__ = cel.@mapInsert(__result__, transform) + // accumulator = cel.@mapInsert(accumulator, transform) step := mef.NewCall(mapInsert, mef.NewAccuIdent(), transform) if filter != nil { - // __result__ = (filter) ? cel.@mapInsert(__result__, transform) : __result__ + // accumulator = (filter) ? cel.@mapInsert(accumulator, transform) : accumulator step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) } return mef.NewComprehensionTwoVar( target, iterVar1, iterVar2, - parser.AccumulatorName, + mef.AccuIdentName(), /*accuInit=*/ mef.NewMap(), /*condition=*/ mef.NewLiteral(types.True), step, @@ -392,10 +410,10 @@ func extractIterVars(mef cel.MacroExprFactory, arg0, arg1 ast.Expr) (string, str if iterVar1 == iterVar2 { return "", "", mef.NewError(arg1.ID(), fmt.Sprintf("duplicate variable name: %s", iterVar1)) } - if iterVar1 == parser.AccumulatorName { + if iterVar1 == mef.AccuIdentName() || iterVar1 == parser.AccumulatorName { return "", "", mef.NewError(arg0.ID(), "iteration variable overwrites accumulator variable") } - if iterVar2 == parser.AccumulatorName { + if iterVar2 == mef.AccuIdentName() || iterVar2 == parser.AccumulatorName { return "", "", mef.NewError(arg1.ID(), "iteration variable overwrites accumulator variable") } return iterVar1, iterVar2, nil diff --git a/e2e/vendor/github.com/google/cel-go/ext/encoders.go b/e2e/vendor/github.com/google/cel-go/ext/encoders.go index ac04b1a7b..731c3d095 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/encoders.go +++ b/e2e/vendor/github.com/google/cel-go/ext/encoders.go @@ -16,6 +16,7 @@ package ext import ( "encoding/base64" + "math" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" @@ -47,17 +48,34 @@ import ( // Examples: // // base64.encode(b'hello') // return b'aGVsbG8=' -func Encoders() cel.EnvOption { - return cel.Lib(encoderLib{}) +func Encoders(options ...EncodersOption) cel.EnvOption { + l := &encoderLib{version: math.MaxUint32} + for _, o := range options { + l = o(l) + } + return cel.Lib(l) } -type encoderLib struct{} +// EncodersOption declares a functional operator for configuring encoder extensions. +type EncodersOption func(*encoderLib) *encoderLib -func (encoderLib) LibraryName() string { +// EncodersVersion sets the library version for encoder extensions. +func EncodersVersion(version uint32) EncodersOption { + return func(lib *encoderLib) *encoderLib { + lib.version = version + return lib + } +} + +type encoderLib struct { + version uint32 +} + +func (*encoderLib) LibraryName() string { return "cel.lib.ext.encoders" } -func (encoderLib) CompileOptions() []cel.EnvOption { +func (*encoderLib) CompileOptions() []cel.EnvOption { return []cel.EnvOption{ cel.Function("base64.decode", cel.Overload("base64_decode_string", []*cel.Type{cel.StringType}, cel.BytesType, @@ -74,7 +92,7 @@ func (encoderLib) CompileOptions() []cel.EnvOption { } } -func (encoderLib) ProgramOptions() []cel.ProgramOption { +func (*encoderLib) ProgramOptions() []cel.ProgramOption { return []cel.ProgramOption{} } diff --git a/e2e/vendor/github.com/google/cel-go/ext/formatting.go b/e2e/vendor/github.com/google/cel-go/ext/formatting.go index dbff613b2..932d562ec 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/formatting.go +++ b/e2e/vendor/github.com/google/cel-go/ext/formatting.go @@ -434,7 +434,7 @@ func (stringFormatValidator) Validate(env *cel.Env, _ cel.ValidatorConfig, a *as // use a placeholder locale, since locale doesn't affect syntax _, err := parseFormatString(formatStr, formatCheck, formatCheck, "en_US") if err != nil { - iss.ReportErrorAtID(getErrorExprID(e.ID(), err), err.Error()) + iss.ReportErrorAtID(getErrorExprID(e.ID(), err), "%v", err) continue } seenArgs := formatCheck.argsRequested diff --git a/e2e/vendor/github.com/google/cel-go/ext/guards.go b/e2e/vendor/github.com/google/cel-go/ext/guards.go index ccede289f..1461c0416 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/guards.go +++ b/e2e/vendor/github.com/google/cel-go/ext/guards.go @@ -24,28 +24,28 @@ import ( func intOrError(i int64, err error) ref.Val { if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Int(i) } func bytesOrError(bytes []byte, err error) ref.Val { if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.Bytes(bytes) } func stringOrError(str string, err error) ref.Val { if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.String(str) } func listStringOrError(strs []string, err error) ref.Val { if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return types.DefaultTypeAdapter.NativeToValue(strs) } diff --git a/e2e/vendor/github.com/google/cel-go/ext/lists.go b/e2e/vendor/github.com/google/cel-go/ext/lists.go index d0b90ea92..675ea8672 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/lists.go +++ b/e2e/vendor/github.com/google/cel-go/ext/lists.go @@ -145,13 +145,10 @@ var comparableTypes = []*cel.Type{ // == ["bar", "foo", "baz"] func Lists(options ...ListsOption) cel.EnvOption { - l := &listsLib{ - version: math.MaxUint32, - } + l := &listsLib{version: math.MaxUint32} for _, o := range options { l = o(l) } - return cel.Lib(l) } @@ -211,9 +208,10 @@ func (lib listsLib) CompileOptions() []cel.EnvOption { cel.MemberOverload("list_flatten", []*cel.Type{listListType}, listType, cel.UnaryBinding(func(arg ref.Val) ref.Val { + // double-check as type-guards disabled list, ok := arg.(traits.Lister) if !ok { - return types.MaybeNoSuchOverloadErr(arg) + return types.ValOrErr(arg, "no such overload: %v.flatten()", arg.Type()) } flatList, err := flatten(list, 1) if err != nil { @@ -226,13 +224,14 @@ func (lib listsLib) CompileOptions() []cel.EnvOption { cel.MemberOverload("list_flatten_int", []*cel.Type{listDyn, types.IntType}, listDyn, cel.BinaryBinding(func(arg1, arg2 ref.Val) ref.Val { + // double-check as type-guards disabled list, ok := arg1.(traits.Lister) if !ok { - return types.MaybeNoSuchOverloadErr(arg1) + return types.ValOrErr(arg1, "no such overload: %v.flatten(%v)", arg1.Type(), arg2.Type()) } depth, ok := arg2.(types.Int) if !ok { - return types.MaybeNoSuchOverloadErr(arg2) + return types.ValOrErr(arg1, "no such overload: %v.flatten(%v)", arg1.Type(), arg2.Type()) } flatList, err := flatten(list, int64(depth)) if err != nil { @@ -260,10 +259,8 @@ func (lib listsLib) CompileOptions() []cel.EnvOption { }), cel.SingletonUnaryBinding( func(arg ref.Val) ref.Val { - list, ok := arg.(traits.Lister) - if !ok { - return types.MaybeNoSuchOverloadErr(arg) - } + // validated by type-guards + list := arg.(traits.Lister) sorted, err := sortList(list) if err != nil { return types.WrapErr(err) @@ -287,15 +284,10 @@ func (lib listsLib) CompileOptions() []cel.EnvOption { ) }), cel.SingletonBinaryBinding( - func(arg1 ref.Val, arg2 ref.Val) ref.Val { - list, ok := arg1.(traits.Lister) - if !ok { - return types.MaybeNoSuchOverloadErr(arg1) - } - keys, ok := arg2.(traits.Lister) - if !ok { - return types.MaybeNoSuchOverloadErr(arg2) - } + func(arg1, arg2 ref.Val) ref.Val { + // validated by type-guards + list := arg1.(traits.Lister) + keys := arg2.(traits.Lister) sorted, err := sortListByAssociatedKeys(list, keys) if err != nil { return types.WrapErr(err) @@ -498,8 +490,9 @@ func sortByMacro(meh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (as if targetKind != ast.ListKind && targetKind != ast.SelectKind && targetKind != ast.IdentKind && - targetKind != ast.ComprehensionKind && targetKind != ast.CallKind { - return nil, meh.NewError(target.ID(), fmt.Sprintf("sortBy can only be applied to a list, identifier, comprehension, call or select expression")) + targetKind != ast.ComprehensionKind && + targetKind != ast.CallKind { + return nil, meh.NewError(target.ID(), "sortBy can only be applied to a list, identifier, comprehension, call or select expression") } mapCompr, err := parser.MakeMap(meh, meh.Copy(varIdent), args) diff --git a/e2e/vendor/github.com/google/cel-go/ext/native.go b/e2e/vendor/github.com/google/cel-go/ext/native.go index 36ab4a7ae..1c33def49 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/native.go +++ b/e2e/vendor/github.com/google/cel-go/ext/native.go @@ -17,6 +17,7 @@ package ext import ( "errors" "fmt" + "math" "reflect" "strings" "time" @@ -98,7 +99,9 @@ var ( func NativeTypes(args ...any) cel.EnvOption { return func(env *cel.Env) (*cel.Env, error) { nativeTypes := make([]any, 0, len(args)) - tpOptions := nativeTypeOptions{} + tpOptions := nativeTypeOptions{ + version: math.MaxUint32, + } for _, v := range args { switch v := v.(type) { @@ -128,6 +131,14 @@ func NativeTypes(args ...any) cel.EnvOption { // NativeTypesOption is a functional interface for configuring handling of native types. type NativeTypesOption func(*nativeTypeOptions) error +// NativeTypesVersion sets the native types version support for native extensions functions. +func NativeTypesVersion(version uint32) NativeTypesOption { + return func(opts *nativeTypeOptions) error { + opts.version = version + return nil + } +} + // NativeTypesFieldNameHandler is a handler for mapping a reflect.StructField to a CEL field name. // This can be used to override the default Go struct field to CEL field name mapping. type NativeTypesFieldNameHandler = func(field reflect.StructField) string @@ -158,6 +169,9 @@ type nativeTypeOptions struct { // This is most commonly used for switching to parsing based off the struct field tag, // such as "cel" or "json". fieldNameHandler NativeTypesFieldNameHandler + + // version is the native types library version. + version uint32 } // ParseStructTags configures if native types field names should be overridable by CEL struct tags. @@ -329,7 +343,7 @@ func (tp *nativeTypeProvider) NewValue(typeName string, fields map[string]ref.Va } fieldVal, err := val.ConvertToNative(refFieldDef.Type) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } refField := refVal.FieldByIndex(refFieldDef.Index) refFieldVal := reflect.ValueOf(fieldVal) @@ -436,7 +450,7 @@ func convertToCelType(refType reflect.Type) (*cel.Type, bool) { func (tp *nativeTypeProvider) newNativeObject(val any, refValue reflect.Value) ref.Val { valType, err := newNativeType(tp.options.fieldNameHandler, refValue.Type()) if err != nil { - return types.NewErr(err.Error()) + return types.NewErrFromString(err.Error()) } return &nativeObj{ Adapter: tp, diff --git a/e2e/vendor/github.com/google/cel-go/ext/protos.go b/e2e/vendor/github.com/google/cel-go/ext/protos.go index 68796f60a..b09db25b0 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/protos.go +++ b/e2e/vendor/github.com/google/cel-go/ext/protos.go @@ -15,6 +15,8 @@ package ext import ( + "math" + "github.com/google/cel-go/cel" "github.com/google/cel-go/common/ast" ) @@ -49,8 +51,23 @@ import ( // Examples: // // proto.hasExt(msg, google.expr.proto2.test.int32_ext) // returns true || false -func Protos() cel.EnvOption { - return cel.Lib(protoLib{}) +func Protos(options ...ProtosOption) cel.EnvOption { + l := &protoLib{version: math.MaxUint32} + for _, o := range options { + l = o(l) + } + return cel.Lib(l) +} + +// ProtosOption declares a functional operator for configuring protobuf utilities. +type ProtosOption func(*protoLib) *protoLib + +// ProtosVersion sets the library version for extensions for protobuf utilities. +func ProtosVersion(version uint32) ProtosOption { + return func(lib *protoLib) *protoLib { + lib.version = version + return lib + } } var ( @@ -59,7 +76,9 @@ var ( getExtension = "getExt" ) -type protoLib struct{} +type protoLib struct { + version uint32 +} // LibraryName implements the SingletonLibrary interface method. func (protoLib) LibraryName() string { diff --git a/e2e/vendor/github.com/google/cel-go/ext/sets.go b/e2e/vendor/github.com/google/cel-go/ext/sets.go index 7e9416655..9a9ef6eef 100644 --- a/e2e/vendor/github.com/google/cel-go/ext/sets.go +++ b/e2e/vendor/github.com/google/cel-go/ext/sets.go @@ -77,11 +77,28 @@ import ( // sets.intersects([1], []) // false // sets.intersects([1], [1, 2]) // true // sets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // true -func Sets() cel.EnvOption { - return cel.Lib(setsLib{}) +func Sets(options ...SetsOption) cel.EnvOption { + l := &setsLib{} + for _, o := range options { + l = o(l) + } + return cel.Lib(l) } -type setsLib struct{} +// SetsOption declares a functional operator for configuring set extensions. +type SetsOption func(*setsLib) *setsLib + +// SetsVersion sets the library version for set extensions. +func SetsVersion(version uint32) SetsOption { + return func(lib *setsLib) *setsLib { + lib.version = version + return lib + } +} + +type setsLib struct { + version uint32 +} // LibraryName implements the SingletonLibrary interface method. func (setsLib) LibraryName() string { diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/activation.go b/e2e/vendor/github.com/google/cel-go/interpreter/activation.go index 1577f3590..c20d19de1 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/activation.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/activation.go @@ -156,6 +156,11 @@ type PartialActivation interface { UnknownAttributePatterns() []*AttributePattern } +// partialActivationConverter indicates whether an Activation implementation supports conversion to a PartialActivation +type partialActivationConverter interface { + asPartialActivation() (PartialActivation, bool) +} + // partActivation is the default implementations of the PartialActivation interface. type partActivation struct { Activation @@ -166,3 +171,20 @@ type partActivation struct { func (a *partActivation) UnknownAttributePatterns() []*AttributePattern { return a.unknowns } + +// asPartialActivation returns the partActivation as a PartialActivation interface. +func (a *partActivation) asPartialActivation() (PartialActivation, bool) { + return a, true +} + +func asPartialActivation(vars Activation) (PartialActivation, bool) { + // Only internal activation instances may implement this interface + if pv, ok := vars.(partialActivationConverter); ok { + return pv.asPartialActivation() + } + // Since Activations may be hierarchical, test whether a parent converts to a PartialActivation + if vars.Parent() != nil { + return asPartialActivation(vars.Parent()) + } + return nil, false +} diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go b/e2e/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go index 8f19bde7e..7e5c2db0f 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/attribute_patterns.go @@ -358,7 +358,7 @@ func (m *attributeMatcher) AddQualifier(qual Qualifier) (Attribute, error) { func (m *attributeMatcher) Resolve(vars Activation) (any, error) { id := m.NamespacedAttribute.ID() // Bug in how partial activation is resolved, should search parents as well. - partial, isPartial := toPartialActivation(vars) + partial, isPartial := asPartialActivation(vars) if isPartial { unk, err := m.fac.matchesUnknownPatterns( partial, @@ -384,14 +384,3 @@ func (m *attributeMatcher) Qualify(vars Activation, obj any) (any, error) { func (m *attributeMatcher) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) { return attrQualifyIfPresent(m.fac, vars, obj, m, presenceOnly) } - -func toPartialActivation(vars Activation) (PartialActivation, bool) { - pv, ok := vars.(PartialActivation) - if ok { - return pv, true - } - if vars.Parent() != nil { - return toPartialActivation(vars.Parent()) - } - return nil, false -} diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/interpretable.go b/e2e/vendor/github.com/google/cel-go/interpreter/interpretable.go index ebc432e9d..591b7688b 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/interpretable.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/interpretable.go @@ -762,6 +762,9 @@ func (fold *evalFold) Eval(ctx Activation) ref.Val { defer releaseFolder(f) foldRange := fold.iterRange.Eval(ctx) + if types.IsUnknownOrError(foldRange) { + return foldRange + } if fold.iterVar2 != "" { var foldable traits.Foldable switch r := foldRange.(type) { @@ -1241,7 +1244,7 @@ func invalidOptionalElementInit(value ref.Val) ref.Val { func newFolder(eval *evalFold, ctx Activation) *folder { f := folderPool.Get().(*folder) f.evalFold = eval - f.Activation = ctx + f.activation = ctx return f } @@ -1262,7 +1265,7 @@ func releaseFolder(f *folder) { // cel.bind or cel.@block. type folder struct { *evalFold - Activation + activation Activation // fold state objects. accuVal ref.Val @@ -1290,7 +1293,7 @@ func (f *folder) foldIterable(iterable traits.Iterable) ref.Val { // Update the accumulation value and check for eval interuption. f.accuVal = f.step.Eval(f) f.initialized = true - if f.interruptable && checkInterrupt(f.Activation) { + if f.interruptable && checkInterrupt(f.activation) { f.interrupted = true return f.evalResult() } @@ -1316,7 +1319,7 @@ func (f *folder) FoldEntry(key, val any) bool { // Update the accumulation value and check for eval interuption. f.accuVal = f.step.Eval(f) f.initialized = true - if f.interruptable && checkInterrupt(f.Activation) { + if f.interruptable && checkInterrupt(f.activation) { f.interrupted = true return false } @@ -1330,7 +1333,7 @@ func (f *folder) ResolveName(name string) (any, bool) { if name == f.accuVar { if !f.initialized { f.initialized = true - initVal := f.accu.Eval(f.Activation) + initVal := f.accu.Eval(f.activation) if !f.exhaustive { if l, isList := initVal.(traits.Lister); isList && l.Size() == types.IntZero { initVal = types.NewMutableList(f.adapter) @@ -1355,7 +1358,32 @@ func (f *folder) ResolveName(name string) (any, bool) { return f.iterVar2Val, true } } - return f.Activation.ResolveName(name) + return f.activation.ResolveName(name) +} + +// Parent returns the activation embedded into the folder. +func (f *folder) Parent() Activation { + return f.activation +} + +// UnknownAttributePatterns implements the PartialActivation interface returning the unknown patterns +// if they were provided to the input activation, or an empty set if the proxied activation is not partial. +func (f *folder) UnknownAttributePatterns() []*AttributePattern { + if pv, ok := f.activation.(partialActivationConverter); ok { + if partial, isPartial := pv.asPartialActivation(); isPartial { + return partial.UnknownAttributePatterns() + } + } + return []*AttributePattern{} +} + +func (f *folder) asPartialActivation() (PartialActivation, bool) { + if pv, ok := f.activation.(partialActivationConverter); ok { + if _, isPartial := pv.asPartialActivation(); isPartial { + return f, true + } + } + return nil, false } // evalResult computes the final result of the fold after all entries have been folded and accumulated. @@ -1381,7 +1409,7 @@ func (f *folder) evalResult() ref.Val { // reset clears any state associated with folder evaluation. func (f *folder) reset() { f.evalFold = nil - f.Activation = nil + f.activation = nil f.accuVal = nil f.iterVar1Val = nil f.iterVar2Val = nil diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/planner.go b/e2e/vendor/github.com/google/cel-go/interpreter/planner.go index 3d918ce87..f0fd4eaf9 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/planner.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/planner.go @@ -506,7 +506,7 @@ func (p *planner) planCreateList(expr ast.Expr) (Interpretable, error) { id: expr.ID(), elems: elems, optionals: optionals, - hasOptionals: len(optionals) != 0, + hasOptionals: len(optionalIndices) != 0, adapter: p.adapter, }, nil } @@ -518,6 +518,7 @@ func (p *planner) planCreateMap(expr ast.Expr) (Interpretable, error) { optionals := make([]bool, len(entries)) keys := make([]Interpretable, len(entries)) vals := make([]Interpretable, len(entries)) + hasOptionals := false for i, e := range entries { entry := e.AsMapEntry() keyVal, err := p.Plan(entry.Key()) @@ -532,13 +533,14 @@ func (p *planner) planCreateMap(expr ast.Expr) (Interpretable, error) { } vals[i] = valVal optionals[i] = entry.IsOptional() + hasOptionals = hasOptionals || entry.IsOptional() } return &evalMap{ id: expr.ID(), keys: keys, vals: vals, optionals: optionals, - hasOptionals: len(optionals) != 0, + hasOptionals: hasOptionals, adapter: p.adapter, }, nil } @@ -554,6 +556,7 @@ func (p *planner) planCreateStruct(expr ast.Expr) (Interpretable, error) { optionals := make([]bool, len(objFields)) fields := make([]string, len(objFields)) vals := make([]Interpretable, len(objFields)) + hasOptionals := false for i, f := range objFields { field := f.AsStructField() fields[i] = field.Name() @@ -563,6 +566,7 @@ func (p *planner) planCreateStruct(expr ast.Expr) (Interpretable, error) { } vals[i] = val optionals[i] = field.IsOptional() + hasOptionals = hasOptionals || field.IsOptional() } return &evalObj{ id: expr.ID(), @@ -570,7 +574,7 @@ func (p *planner) planCreateStruct(expr ast.Expr) (Interpretable, error) { fields: fields, vals: vals, optionals: optionals, - hasOptionals: len(optionals) != 0, + hasOptionals: hasOptionals, provider: p.provider, }, nil } diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/prune.go b/e2e/vendor/github.com/google/cel-go/interpreter/prune.go index 410d80dc4..1662c1c1b 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/prune.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/prune.go @@ -88,7 +88,7 @@ func PruneAst(expr ast.Expr, macroCalls map[int64]ast.Expr, state EvalState) *as func (p *astPruner) maybeCreateLiteral(id int64, val ref.Val) (ast.Expr, bool) { switch v := val.(type) { - case types.Bool, types.Bytes, types.Double, types.Int, types.Null, types.String, types.Uint: + case types.Bool, types.Bytes, types.Double, types.Int, types.Null, types.String, types.Uint, *types.Optional: p.state.SetValue(id, val) return p.NewLiteral(id, val), true case types.Duration: @@ -281,13 +281,29 @@ func (p *astPruner) prune(node ast.Expr) (ast.Expr, bool) { } if macro, found := p.macroCalls[node.ID()]; found { // Ensure that intermediate values for the comprehension are cleared during pruning + pruneMacroCall := node.Kind() != ast.UnspecifiedExprKind if node.Kind() == ast.ComprehensionKind { - compre := node.AsComprehension() - visit(macro, clearIterVarVisitor(compre.IterVar(), p.state)) + // Only prune cel.bind() calls since the variables of the comprehension are all + // visible to the user, so there's no chance of an incorrect value being observed + // as a result of looking at intermediate computations within a comprehension. + pruneMacroCall = isCelBindMacro(macro) } - // prune the expression in terms of the macro call instead of the expanded form. - if newMacro, pruned := p.prune(macro); pruned { - p.macroCalls[node.ID()] = newMacro + if pruneMacroCall { + // prune the expression in terms of the macro call instead of the expanded form when + // dealing with macro call tracking references. + if newMacro, pruned := p.prune(macro); pruned { + p.macroCalls[node.ID()] = newMacro + } + } else { + // Otherwise just prune the macro target in keeping with the pruning behavior of the + // comprehensions later in the call graph. + macroCall := macro.AsCall() + if macroCall.Target() != nil { + if newTarget, pruned := p.prune(macroCall.Target()); pruned { + macro = p.NewMemberCall(macro.ID(), macroCall.FunctionName(), newTarget, macroCall.Args()...) + p.macroCalls[node.ID()] = macro + } + } } } @@ -421,6 +437,19 @@ func (p *astPruner) prune(node ast.Expr) (ast.Expr, bool) { // the last iteration of the comprehension and not each step in the evaluation which // means that the any residuals computed in between might be inaccurate. if newRange, pruned := p.maybePrune(compre.IterRange()); pruned { + if compre.HasIterVar2() { + return p.NewComprehensionTwoVar( + node.ID(), + newRange, + compre.IterVar(), + compre.IterVar2(), + compre.AccuVar(), + compre.AccuInit(), + compre.LoopCondition(), + compre.LoopStep(), + compre.Result(), + ), true + } return p.NewComprehension( node.ID(), newRange, @@ -468,16 +497,6 @@ func getMaxID(expr ast.Expr) int64 { return maxID } -func clearIterVarVisitor(varName string, state EvalState) astVisitor { - return astVisitor{ - visitExpr: func(e ast.Expr) { - if e.Kind() == ast.IdentKind && e.AsIdent() == varName { - state.SetValue(e.ID(), nil) - } - }, - } -} - func maxIDVisitor(maxID *int64) astVisitor { return astVisitor{ visitExpr: func(e ast.Expr) { @@ -541,3 +560,15 @@ func visit(expr ast.Expr, visitor astVisitor) { } } } + +func isCelBindMacro(macro ast.Expr) bool { + if macro.Kind() != ast.CallKind { + return false + } + macroCall := macro.AsCall() + target := macroCall.Target() + return macroCall.FunctionName() == "bind" && + macroCall.IsMemberFunction() && + target.Kind() == ast.IdentKind && + target.AsIdent() == "cel" +} diff --git a/e2e/vendor/github.com/google/cel-go/interpreter/runtimecost.go b/e2e/vendor/github.com/google/cel-go/interpreter/runtimecost.go index b9b307c15..8f47c53d2 100644 --- a/e2e/vendor/github.com/google/cel-go/interpreter/runtimecost.go +++ b/e2e/vendor/github.com/google/cel-go/interpreter/runtimecost.go @@ -198,20 +198,20 @@ func (c *CostTracker) costCall(call InterpretableCall, args []ref.Val, result re switch call.OverloadID() { // O(n) functions case overloads.StartsWithString, overloads.EndsWithString, overloads.StringToBytes, overloads.BytesToString, overloads.ExtQuoteString, overloads.ExtFormatString: - cost += uint64(math.Ceil(float64(c.actualSize(args[0])) * common.StringTraversalCostFactor)) + cost += uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor)) case overloads.InList: // If a list is composed entirely of constant values this is O(1), but we don't account for that here. // We just assume all list containment checks are O(n). - cost += c.actualSize(args[1]) + cost += actualSize(args[1]) // O(min(m, n)) functions case overloads.LessString, overloads.GreaterString, overloads.LessEqualsString, overloads.GreaterEqualsString, overloads.LessBytes, overloads.GreaterBytes, overloads.LessEqualsBytes, overloads.GreaterEqualsBytes, overloads.Equals, overloads.NotEquals: // When we check the equality of 2 scalar values (e.g. 2 integers, 2 floating-point numbers, 2 booleans etc.), - // the CostTracker.actualSize() function by definition returns 1 for each operand, resulting in an overall cost + // the CostTracker.ActualSize() function by definition returns 1 for each operand, resulting in an overall cost // of 1. - lhsSize := c.actualSize(args[0]) - rhsSize := c.actualSize(args[1]) + lhsSize := actualSize(args[0]) + rhsSize := actualSize(args[1]) minSize := lhsSize if rhsSize < minSize { minSize = rhsSize @@ -220,23 +220,23 @@ func (c *CostTracker) costCall(call InterpretableCall, args []ref.Val, result re // O(m+n) functions case overloads.AddString, overloads.AddBytes: // In the worst case scenario, we would need to reallocate a new backing store and copy both operands over. - cost += uint64(math.Ceil(float64(c.actualSize(args[0])+c.actualSize(args[1])) * common.StringTraversalCostFactor)) + cost += uint64(math.Ceil(float64(actualSize(args[0])+actualSize(args[1])) * common.StringTraversalCostFactor)) // O(nm) functions case overloads.MatchesString: // https://swtch.com/~rsc/regexp/regexp1.html applies to RE2 implementation supported by CEL // Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0 // in case where string is empty but regex is still expensive. - strCost := uint64(math.Ceil((1.0 + float64(c.actualSize(args[0]))) * common.StringTraversalCostFactor)) + strCost := uint64(math.Ceil((1.0 + float64(actualSize(args[0]))) * common.StringTraversalCostFactor)) // We don't know how many expressions are in the regex, just the string length (a huge // improvement here would be to somehow get a count the number of expressions in the regex or // how many states are in the regex state machine and use that to measure regex cost). // For now, we're making a guess that each expression in a regex is typically at least 4 chars // in length. - regexCost := uint64(math.Ceil(float64(c.actualSize(args[1])) * common.RegexStringLengthCostFactor)) + regexCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.RegexStringLengthCostFactor)) cost += strCost * regexCost case overloads.ContainsString: - strCost := uint64(math.Ceil(float64(c.actualSize(args[0])) * common.StringTraversalCostFactor)) - substrCost := uint64(math.Ceil(float64(c.actualSize(args[1])) * common.StringTraversalCostFactor)) + strCost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor)) + substrCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.StringTraversalCostFactor)) cost += strCost * substrCost default: @@ -253,11 +253,15 @@ func (c *CostTracker) costCall(call InterpretableCall, args []ref.Val, result re return cost } -// actualSize returns the size of value -func (c *CostTracker) actualSize(value ref.Val) uint64 { +// actualSize returns the size of the value for all traits.Sizer values, a fixed size for all proto-based +// objects, and a size of 1 for all other value types. +func actualSize(value ref.Val) uint64 { if sz, ok := value.(traits.Sizer); ok { return uint64(sz.Size().(types.Int)) } + if opt, ok := value.(*types.Optional); ok && opt.HasValue() { + return actualSize(opt.GetValue()) + } return 1 } diff --git a/e2e/vendor/github.com/google/cel-go/parser/errors.go b/e2e/vendor/github.com/google/cel-go/parser/errors.go index 93ae7a3ad..c3cec01a8 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/errors.go +++ b/e2e/vendor/github.com/google/cel-go/parser/errors.go @@ -15,8 +15,6 @@ package parser import ( - "fmt" - "github.com/google/cel-go/common" ) @@ -31,11 +29,11 @@ func (e *parseErrors) errorCount() int { } func (e *parseErrors) internalError(message string) { - e.errs.ReportErrorAtID(0, common.NoLocation, message) + e.errs.ReportErrorAtID(0, common.NoLocation, "%s", message) } func (e *parseErrors) syntaxError(l common.Location, message string) { - e.errs.ReportErrorAtID(0, l, fmt.Sprintf("Syntax error: %s", message)) + e.errs.ReportErrorAtID(0, l, "Syntax error: %s", message) } func (e *parseErrors) reportErrorAtID(id int64, l common.Location, message string, args ...any) { diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.g4 b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.g4 index b011da803..ee53a844b 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.g4 +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.g4 @@ -52,13 +52,14 @@ unary member : primary # PrimaryExpr - | member op='.' (opt='?')? id=IDENTIFIER # Select + | member op='.' (opt='?')? id=escapeIdent # Select | member op='.' id=IDENTIFIER open='(' args=exprList? ')' # MemberCall | member op='[' (opt='?')? index=expr ']' # Index ; primary - : leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall + : leadingDot='.'? id=IDENTIFIER # Ident + | leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')') # GlobalCall | '(' e=expr ')' # Nested | op='[' elems=listInit? ','? ']' # CreateList | op='{' entries=mapInitializerList? ','? '}' # CreateStruct @@ -80,13 +81,18 @@ fieldInitializerList ; optField - : (opt='?')? IDENTIFIER + : (opt='?')? escapeIdent ; mapInitializerList : keys+=optExpr cols+=':' values+=expr (',' keys+=optExpr cols+=':' values+=expr)* ; +escapeIdent + : id=IDENTIFIER # SimpleIdentifier + | id=ESC_IDENTIFIER # EscapedIdentifier +; + optExpr : (opt='?')? e=expr ; @@ -198,3 +204,4 @@ STRING BYTES : ('b' | 'B') STRING; IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*; +ESC_IDENTIFIER : '`' (LETTER | DIGIT | '_' | '.' | '-' | '/' | ' ')+ '`'; \ No newline at end of file diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.interp b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.interp index 75b8bb3e2..e085bab57 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.interp +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.interp @@ -36,6 +36,7 @@ null null null null +null token symbolic names: null @@ -75,6 +76,7 @@ NUM_UINT STRING BYTES IDENTIFIER +ESC_IDENTIFIER rule names: start @@ -91,9 +93,10 @@ listInit fieldInitializerList optField mapInitializerList +escapeIdent optExpr literal atn: -[4, 1, 36, 251, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 42, 8, 1, 1, 2, 1, 2, 1, 2, 5, 2, 47, 8, 2, 10, 2, 12, 2, 50, 9, 2, 1, 3, 1, 3, 1, 3, 5, 3, 55, 8, 3, 10, 3, 12, 3, 58, 9, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 5, 4, 66, 8, 4, 10, 4, 12, 4, 69, 9, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 80, 8, 5, 10, 5, 12, 5, 83, 9, 5, 1, 6, 1, 6, 4, 6, 87, 8, 6, 11, 6, 12, 6, 88, 1, 6, 1, 6, 4, 6, 93, 8, 6, 11, 6, 12, 6, 94, 1, 6, 3, 6, 98, 8, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 106, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 114, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 120, 8, 7, 1, 7, 1, 7, 1, 7, 5, 7, 125, 8, 7, 10, 7, 12, 7, 128, 9, 7, 1, 8, 3, 8, 131, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 136, 8, 8, 1, 8, 3, 8, 139, 8, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 3, 8, 147, 8, 8, 1, 8, 3, 8, 150, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 155, 8, 8, 1, 8, 3, 8, 158, 8, 8, 1, 8, 1, 8, 3, 8, 162, 8, 8, 1, 8, 1, 8, 1, 8, 5, 8, 167, 8, 8, 10, 8, 12, 8, 170, 9, 8, 1, 8, 1, 8, 3, 8, 174, 8, 8, 1, 8, 3, 8, 177, 8, 8, 1, 8, 1, 8, 3, 8, 181, 8, 8, 1, 9, 1, 9, 1, 9, 5, 9, 186, 8, 9, 10, 9, 12, 9, 189, 9, 9, 1, 10, 1, 10, 1, 10, 5, 10, 194, 8, 10, 10, 10, 12, 10, 197, 9, 10, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 5, 11, 207, 8, 11, 10, 11, 12, 11, 210, 9, 11, 1, 12, 3, 12, 213, 8, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 5, 13, 225, 8, 13, 10, 13, 12, 13, 228, 9, 13, 1, 14, 3, 14, 231, 8, 14, 1, 14, 1, 14, 1, 15, 3, 15, 236, 8, 15, 1, 15, 1, 15, 1, 15, 3, 15, 241, 8, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 249, 8, 15, 1, 15, 0, 3, 8, 10, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 0, 3, 1, 0, 1, 7, 1, 0, 23, 25, 2, 0, 18, 18, 22, 22, 281, 0, 32, 1, 0, 0, 0, 2, 35, 1, 0, 0, 0, 4, 43, 1, 0, 0, 0, 6, 51, 1, 0, 0, 0, 8, 59, 1, 0, 0, 0, 10, 70, 1, 0, 0, 0, 12, 97, 1, 0, 0, 0, 14, 99, 1, 0, 0, 0, 16, 180, 1, 0, 0, 0, 18, 182, 1, 0, 0, 0, 20, 190, 1, 0, 0, 0, 22, 198, 1, 0, 0, 0, 24, 212, 1, 0, 0, 0, 26, 216, 1, 0, 0, 0, 28, 230, 1, 0, 0, 0, 30, 248, 1, 0, 0, 0, 32, 33, 3, 2, 1, 0, 33, 34, 5, 0, 0, 1, 34, 1, 1, 0, 0, 0, 35, 41, 3, 4, 2, 0, 36, 37, 5, 20, 0, 0, 37, 38, 3, 4, 2, 0, 38, 39, 5, 21, 0, 0, 39, 40, 3, 2, 1, 0, 40, 42, 1, 0, 0, 0, 41, 36, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 3, 1, 0, 0, 0, 43, 48, 3, 6, 3, 0, 44, 45, 5, 9, 0, 0, 45, 47, 3, 6, 3, 0, 46, 44, 1, 0, 0, 0, 47, 50, 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 5, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 51, 56, 3, 8, 4, 0, 52, 53, 5, 8, 0, 0, 53, 55, 3, 8, 4, 0, 54, 52, 1, 0, 0, 0, 55, 58, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, 57, 1, 0, 0, 0, 57, 7, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 59, 60, 6, 4, -1, 0, 60, 61, 3, 10, 5, 0, 61, 67, 1, 0, 0, 0, 62, 63, 10, 1, 0, 0, 63, 64, 7, 0, 0, 0, 64, 66, 3, 8, 4, 2, 65, 62, 1, 0, 0, 0, 66, 69, 1, 0, 0, 0, 67, 65, 1, 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 9, 1, 0, 0, 0, 69, 67, 1, 0, 0, 0, 70, 71, 6, 5, -1, 0, 71, 72, 3, 12, 6, 0, 72, 81, 1, 0, 0, 0, 73, 74, 10, 2, 0, 0, 74, 75, 7, 1, 0, 0, 75, 80, 3, 10, 5, 3, 76, 77, 10, 1, 0, 0, 77, 78, 7, 2, 0, 0, 78, 80, 3, 10, 5, 2, 79, 73, 1, 0, 0, 0, 79, 76, 1, 0, 0, 0, 80, 83, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, 0, 82, 11, 1, 0, 0, 0, 83, 81, 1, 0, 0, 0, 84, 98, 3, 14, 7, 0, 85, 87, 5, 19, 0, 0, 86, 85, 1, 0, 0, 0, 87, 88, 1, 0, 0, 0, 88, 86, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 90, 1, 0, 0, 0, 90, 98, 3, 14, 7, 0, 91, 93, 5, 18, 0, 0, 92, 91, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 92, 1, 0, 0, 0, 94, 95, 1, 0, 0, 0, 95, 96, 1, 0, 0, 0, 96, 98, 3, 14, 7, 0, 97, 84, 1, 0, 0, 0, 97, 86, 1, 0, 0, 0, 97, 92, 1, 0, 0, 0, 98, 13, 1, 0, 0, 0, 99, 100, 6, 7, -1, 0, 100, 101, 3, 16, 8, 0, 101, 126, 1, 0, 0, 0, 102, 103, 10, 3, 0, 0, 103, 105, 5, 16, 0, 0, 104, 106, 5, 20, 0, 0, 105, 104, 1, 0, 0, 0, 105, 106, 1, 0, 0, 0, 106, 107, 1, 0, 0, 0, 107, 125, 5, 36, 0, 0, 108, 109, 10, 2, 0, 0, 109, 110, 5, 16, 0, 0, 110, 111, 5, 36, 0, 0, 111, 113, 5, 14, 0, 0, 112, 114, 3, 18, 9, 0, 113, 112, 1, 0, 0, 0, 113, 114, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 125, 5, 15, 0, 0, 116, 117, 10, 1, 0, 0, 117, 119, 5, 10, 0, 0, 118, 120, 5, 20, 0, 0, 119, 118, 1, 0, 0, 0, 119, 120, 1, 0, 0, 0, 120, 121, 1, 0, 0, 0, 121, 122, 3, 2, 1, 0, 122, 123, 5, 11, 0, 0, 123, 125, 1, 0, 0, 0, 124, 102, 1, 0, 0, 0, 124, 108, 1, 0, 0, 0, 124, 116, 1, 0, 0, 0, 125, 128, 1, 0, 0, 0, 126, 124, 1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, 15, 1, 0, 0, 0, 128, 126, 1, 0, 0, 0, 129, 131, 5, 16, 0, 0, 130, 129, 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, 131, 132, 1, 0, 0, 0, 132, 138, 5, 36, 0, 0, 133, 135, 5, 14, 0, 0, 134, 136, 3, 18, 9, 0, 135, 134, 1, 0, 0, 0, 135, 136, 1, 0, 0, 0, 136, 137, 1, 0, 0, 0, 137, 139, 5, 15, 0, 0, 138, 133, 1, 0, 0, 0, 138, 139, 1, 0, 0, 0, 139, 181, 1, 0, 0, 0, 140, 141, 5, 14, 0, 0, 141, 142, 3, 2, 1, 0, 142, 143, 5, 15, 0, 0, 143, 181, 1, 0, 0, 0, 144, 146, 5, 10, 0, 0, 145, 147, 3, 20, 10, 0, 146, 145, 1, 0, 0, 0, 146, 147, 1, 0, 0, 0, 147, 149, 1, 0, 0, 0, 148, 150, 5, 17, 0, 0, 149, 148, 1, 0, 0, 0, 149, 150, 1, 0, 0, 0, 150, 151, 1, 0, 0, 0, 151, 181, 5, 11, 0, 0, 152, 154, 5, 12, 0, 0, 153, 155, 3, 26, 13, 0, 154, 153, 1, 0, 0, 0, 154, 155, 1, 0, 0, 0, 155, 157, 1, 0, 0, 0, 156, 158, 5, 17, 0, 0, 157, 156, 1, 0, 0, 0, 157, 158, 1, 0, 0, 0, 158, 159, 1, 0, 0, 0, 159, 181, 5, 13, 0, 0, 160, 162, 5, 16, 0, 0, 161, 160, 1, 0, 0, 0, 161, 162, 1, 0, 0, 0, 162, 163, 1, 0, 0, 0, 163, 168, 5, 36, 0, 0, 164, 165, 5, 16, 0, 0, 165, 167, 5, 36, 0, 0, 166, 164, 1, 0, 0, 0, 167, 170, 1, 0, 0, 0, 168, 166, 1, 0, 0, 0, 168, 169, 1, 0, 0, 0, 169, 171, 1, 0, 0, 0, 170, 168, 1, 0, 0, 0, 171, 173, 5, 12, 0, 0, 172, 174, 3, 22, 11, 0, 173, 172, 1, 0, 0, 0, 173, 174, 1, 0, 0, 0, 174, 176, 1, 0, 0, 0, 175, 177, 5, 17, 0, 0, 176, 175, 1, 0, 0, 0, 176, 177, 1, 0, 0, 0, 177, 178, 1, 0, 0, 0, 178, 181, 5, 13, 0, 0, 179, 181, 3, 30, 15, 0, 180, 130, 1, 0, 0, 0, 180, 140, 1, 0, 0, 0, 180, 144, 1, 0, 0, 0, 180, 152, 1, 0, 0, 0, 180, 161, 1, 0, 0, 0, 180, 179, 1, 0, 0, 0, 181, 17, 1, 0, 0, 0, 182, 187, 3, 2, 1, 0, 183, 184, 5, 17, 0, 0, 184, 186, 3, 2, 1, 0, 185, 183, 1, 0, 0, 0, 186, 189, 1, 0, 0, 0, 187, 185, 1, 0, 0, 0, 187, 188, 1, 0, 0, 0, 188, 19, 1, 0, 0, 0, 189, 187, 1, 0, 0, 0, 190, 195, 3, 28, 14, 0, 191, 192, 5, 17, 0, 0, 192, 194, 3, 28, 14, 0, 193, 191, 1, 0, 0, 0, 194, 197, 1, 0, 0, 0, 195, 193, 1, 0, 0, 0, 195, 196, 1, 0, 0, 0, 196, 21, 1, 0, 0, 0, 197, 195, 1, 0, 0, 0, 198, 199, 3, 24, 12, 0, 199, 200, 5, 21, 0, 0, 200, 208, 3, 2, 1, 0, 201, 202, 5, 17, 0, 0, 202, 203, 3, 24, 12, 0, 203, 204, 5, 21, 0, 0, 204, 205, 3, 2, 1, 0, 205, 207, 1, 0, 0, 0, 206, 201, 1, 0, 0, 0, 207, 210, 1, 0, 0, 0, 208, 206, 1, 0, 0, 0, 208, 209, 1, 0, 0, 0, 209, 23, 1, 0, 0, 0, 210, 208, 1, 0, 0, 0, 211, 213, 5, 20, 0, 0, 212, 211, 1, 0, 0, 0, 212, 213, 1, 0, 0, 0, 213, 214, 1, 0, 0, 0, 214, 215, 5, 36, 0, 0, 215, 25, 1, 0, 0, 0, 216, 217, 3, 28, 14, 0, 217, 218, 5, 21, 0, 0, 218, 226, 3, 2, 1, 0, 219, 220, 5, 17, 0, 0, 220, 221, 3, 28, 14, 0, 221, 222, 5, 21, 0, 0, 222, 223, 3, 2, 1, 0, 223, 225, 1, 0, 0, 0, 224, 219, 1, 0, 0, 0, 225, 228, 1, 0, 0, 0, 226, 224, 1, 0, 0, 0, 226, 227, 1, 0, 0, 0, 227, 27, 1, 0, 0, 0, 228, 226, 1, 0, 0, 0, 229, 231, 5, 20, 0, 0, 230, 229, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 232, 1, 0, 0, 0, 232, 233, 3, 2, 1, 0, 233, 29, 1, 0, 0, 0, 234, 236, 5, 18, 0, 0, 235, 234, 1, 0, 0, 0, 235, 236, 1, 0, 0, 0, 236, 237, 1, 0, 0, 0, 237, 249, 5, 32, 0, 0, 238, 249, 5, 33, 0, 0, 239, 241, 5, 18, 0, 0, 240, 239, 1, 0, 0, 0, 240, 241, 1, 0, 0, 0, 241, 242, 1, 0, 0, 0, 242, 249, 5, 31, 0, 0, 243, 249, 5, 34, 0, 0, 244, 249, 5, 35, 0, 0, 245, 249, 5, 26, 0, 0, 246, 249, 5, 27, 0, 0, 247, 249, 5, 28, 0, 0, 248, 235, 1, 0, 0, 0, 248, 238, 1, 0, 0, 0, 248, 240, 1, 0, 0, 0, 248, 243, 1, 0, 0, 0, 248, 244, 1, 0, 0, 0, 248, 245, 1, 0, 0, 0, 248, 246, 1, 0, 0, 0, 248, 247, 1, 0, 0, 0, 249, 31, 1, 0, 0, 0, 35, 41, 48, 56, 67, 79, 81, 88, 94, 97, 105, 113, 119, 124, 126, 130, 135, 138, 146, 149, 154, 157, 161, 168, 173, 176, 180, 187, 195, 208, 212, 226, 230, 235, 240, 248] \ No newline at end of file +[4, 1, 37, 259, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 44, 8, 1, 1, 2, 1, 2, 1, 2, 5, 2, 49, 8, 2, 10, 2, 12, 2, 52, 9, 2, 1, 3, 1, 3, 1, 3, 5, 3, 57, 8, 3, 10, 3, 12, 3, 60, 9, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 5, 4, 68, 8, 4, 10, 4, 12, 4, 71, 9, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 82, 8, 5, 10, 5, 12, 5, 85, 9, 5, 1, 6, 1, 6, 4, 6, 89, 8, 6, 11, 6, 12, 6, 90, 1, 6, 1, 6, 4, 6, 95, 8, 6, 11, 6, 12, 6, 96, 1, 6, 3, 6, 100, 8, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 108, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 116, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 122, 8, 7, 1, 7, 1, 7, 1, 7, 5, 7, 127, 8, 7, 10, 7, 12, 7, 130, 9, 7, 1, 8, 3, 8, 133, 8, 8, 1, 8, 1, 8, 3, 8, 137, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 142, 8, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 3, 8, 151, 8, 8, 1, 8, 3, 8, 154, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 159, 8, 8, 1, 8, 3, 8, 162, 8, 8, 1, 8, 1, 8, 3, 8, 166, 8, 8, 1, 8, 1, 8, 1, 8, 5, 8, 171, 8, 8, 10, 8, 12, 8, 174, 9, 8, 1, 8, 1, 8, 3, 8, 178, 8, 8, 1, 8, 3, 8, 181, 8, 8, 1, 8, 1, 8, 3, 8, 185, 8, 8, 1, 9, 1, 9, 1, 9, 5, 9, 190, 8, 9, 10, 9, 12, 9, 193, 9, 9, 1, 10, 1, 10, 1, 10, 5, 10, 198, 8, 10, 10, 10, 12, 10, 201, 9, 10, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 5, 11, 211, 8, 11, 10, 11, 12, 11, 214, 9, 11, 1, 12, 3, 12, 217, 8, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 5, 13, 229, 8, 13, 10, 13, 12, 13, 232, 9, 13, 1, 14, 1, 14, 3, 14, 236, 8, 14, 1, 15, 3, 15, 239, 8, 15, 1, 15, 1, 15, 1, 16, 3, 16, 244, 8, 16, 1, 16, 1, 16, 1, 16, 3, 16, 249, 8, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 3, 16, 257, 8, 16, 1, 16, 0, 3, 8, 10, 14, 17, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 0, 3, 1, 0, 1, 7, 1, 0, 23, 25, 2, 0, 18, 18, 22, 22, 290, 0, 34, 1, 0, 0, 0, 2, 37, 1, 0, 0, 0, 4, 45, 1, 0, 0, 0, 6, 53, 1, 0, 0, 0, 8, 61, 1, 0, 0, 0, 10, 72, 1, 0, 0, 0, 12, 99, 1, 0, 0, 0, 14, 101, 1, 0, 0, 0, 16, 184, 1, 0, 0, 0, 18, 186, 1, 0, 0, 0, 20, 194, 1, 0, 0, 0, 22, 202, 1, 0, 0, 0, 24, 216, 1, 0, 0, 0, 26, 220, 1, 0, 0, 0, 28, 235, 1, 0, 0, 0, 30, 238, 1, 0, 0, 0, 32, 256, 1, 0, 0, 0, 34, 35, 3, 2, 1, 0, 35, 36, 5, 0, 0, 1, 36, 1, 1, 0, 0, 0, 37, 43, 3, 4, 2, 0, 38, 39, 5, 20, 0, 0, 39, 40, 3, 4, 2, 0, 40, 41, 5, 21, 0, 0, 41, 42, 3, 2, 1, 0, 42, 44, 1, 0, 0, 0, 43, 38, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 3, 1, 0, 0, 0, 45, 50, 3, 6, 3, 0, 46, 47, 5, 9, 0, 0, 47, 49, 3, 6, 3, 0, 48, 46, 1, 0, 0, 0, 49, 52, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 50, 51, 1, 0, 0, 0, 51, 5, 1, 0, 0, 0, 52, 50, 1, 0, 0, 0, 53, 58, 3, 8, 4, 0, 54, 55, 5, 8, 0, 0, 55, 57, 3, 8, 4, 0, 56, 54, 1, 0, 0, 0, 57, 60, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 7, 1, 0, 0, 0, 60, 58, 1, 0, 0, 0, 61, 62, 6, 4, -1, 0, 62, 63, 3, 10, 5, 0, 63, 69, 1, 0, 0, 0, 64, 65, 10, 1, 0, 0, 65, 66, 7, 0, 0, 0, 66, 68, 3, 8, 4, 2, 67, 64, 1, 0, 0, 0, 68, 71, 1, 0, 0, 0, 69, 67, 1, 0, 0, 0, 69, 70, 1, 0, 0, 0, 70, 9, 1, 0, 0, 0, 71, 69, 1, 0, 0, 0, 72, 73, 6, 5, -1, 0, 73, 74, 3, 12, 6, 0, 74, 83, 1, 0, 0, 0, 75, 76, 10, 2, 0, 0, 76, 77, 7, 1, 0, 0, 77, 82, 3, 10, 5, 3, 78, 79, 10, 1, 0, 0, 79, 80, 7, 2, 0, 0, 80, 82, 3, 10, 5, 2, 81, 75, 1, 0, 0, 0, 81, 78, 1, 0, 0, 0, 82, 85, 1, 0, 0, 0, 83, 81, 1, 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 11, 1, 0, 0, 0, 85, 83, 1, 0, 0, 0, 86, 100, 3, 14, 7, 0, 87, 89, 5, 19, 0, 0, 88, 87, 1, 0, 0, 0, 89, 90, 1, 0, 0, 0, 90, 88, 1, 0, 0, 0, 90, 91, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 100, 3, 14, 7, 0, 93, 95, 5, 18, 0, 0, 94, 93, 1, 0, 0, 0, 95, 96, 1, 0, 0, 0, 96, 94, 1, 0, 0, 0, 96, 97, 1, 0, 0, 0, 97, 98, 1, 0, 0, 0, 98, 100, 3, 14, 7, 0, 99, 86, 1, 0, 0, 0, 99, 88, 1, 0, 0, 0, 99, 94, 1, 0, 0, 0, 100, 13, 1, 0, 0, 0, 101, 102, 6, 7, -1, 0, 102, 103, 3, 16, 8, 0, 103, 128, 1, 0, 0, 0, 104, 105, 10, 3, 0, 0, 105, 107, 5, 16, 0, 0, 106, 108, 5, 20, 0, 0, 107, 106, 1, 0, 0, 0, 107, 108, 1, 0, 0, 0, 108, 109, 1, 0, 0, 0, 109, 127, 3, 28, 14, 0, 110, 111, 10, 2, 0, 0, 111, 112, 5, 16, 0, 0, 112, 113, 5, 36, 0, 0, 113, 115, 5, 14, 0, 0, 114, 116, 3, 18, 9, 0, 115, 114, 1, 0, 0, 0, 115, 116, 1, 0, 0, 0, 116, 117, 1, 0, 0, 0, 117, 127, 5, 15, 0, 0, 118, 119, 10, 1, 0, 0, 119, 121, 5, 10, 0, 0, 120, 122, 5, 20, 0, 0, 121, 120, 1, 0, 0, 0, 121, 122, 1, 0, 0, 0, 122, 123, 1, 0, 0, 0, 123, 124, 3, 2, 1, 0, 124, 125, 5, 11, 0, 0, 125, 127, 1, 0, 0, 0, 126, 104, 1, 0, 0, 0, 126, 110, 1, 0, 0, 0, 126, 118, 1, 0, 0, 0, 127, 130, 1, 0, 0, 0, 128, 126, 1, 0, 0, 0, 128, 129, 1, 0, 0, 0, 129, 15, 1, 0, 0, 0, 130, 128, 1, 0, 0, 0, 131, 133, 5, 16, 0, 0, 132, 131, 1, 0, 0, 0, 132, 133, 1, 0, 0, 0, 133, 134, 1, 0, 0, 0, 134, 185, 5, 36, 0, 0, 135, 137, 5, 16, 0, 0, 136, 135, 1, 0, 0, 0, 136, 137, 1, 0, 0, 0, 137, 138, 1, 0, 0, 0, 138, 139, 5, 36, 0, 0, 139, 141, 5, 14, 0, 0, 140, 142, 3, 18, 9, 0, 141, 140, 1, 0, 0, 0, 141, 142, 1, 0, 0, 0, 142, 143, 1, 0, 0, 0, 143, 185, 5, 15, 0, 0, 144, 145, 5, 14, 0, 0, 145, 146, 3, 2, 1, 0, 146, 147, 5, 15, 0, 0, 147, 185, 1, 0, 0, 0, 148, 150, 5, 10, 0, 0, 149, 151, 3, 20, 10, 0, 150, 149, 1, 0, 0, 0, 150, 151, 1, 0, 0, 0, 151, 153, 1, 0, 0, 0, 152, 154, 5, 17, 0, 0, 153, 152, 1, 0, 0, 0, 153, 154, 1, 0, 0, 0, 154, 155, 1, 0, 0, 0, 155, 185, 5, 11, 0, 0, 156, 158, 5, 12, 0, 0, 157, 159, 3, 26, 13, 0, 158, 157, 1, 0, 0, 0, 158, 159, 1, 0, 0, 0, 159, 161, 1, 0, 0, 0, 160, 162, 5, 17, 0, 0, 161, 160, 1, 0, 0, 0, 161, 162, 1, 0, 0, 0, 162, 163, 1, 0, 0, 0, 163, 185, 5, 13, 0, 0, 164, 166, 5, 16, 0, 0, 165, 164, 1, 0, 0, 0, 165, 166, 1, 0, 0, 0, 166, 167, 1, 0, 0, 0, 167, 172, 5, 36, 0, 0, 168, 169, 5, 16, 0, 0, 169, 171, 5, 36, 0, 0, 170, 168, 1, 0, 0, 0, 171, 174, 1, 0, 0, 0, 172, 170, 1, 0, 0, 0, 172, 173, 1, 0, 0, 0, 173, 175, 1, 0, 0, 0, 174, 172, 1, 0, 0, 0, 175, 177, 5, 12, 0, 0, 176, 178, 3, 22, 11, 0, 177, 176, 1, 0, 0, 0, 177, 178, 1, 0, 0, 0, 178, 180, 1, 0, 0, 0, 179, 181, 5, 17, 0, 0, 180, 179, 1, 0, 0, 0, 180, 181, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 185, 5, 13, 0, 0, 183, 185, 3, 32, 16, 0, 184, 132, 1, 0, 0, 0, 184, 136, 1, 0, 0, 0, 184, 144, 1, 0, 0, 0, 184, 148, 1, 0, 0, 0, 184, 156, 1, 0, 0, 0, 184, 165, 1, 0, 0, 0, 184, 183, 1, 0, 0, 0, 185, 17, 1, 0, 0, 0, 186, 191, 3, 2, 1, 0, 187, 188, 5, 17, 0, 0, 188, 190, 3, 2, 1, 0, 189, 187, 1, 0, 0, 0, 190, 193, 1, 0, 0, 0, 191, 189, 1, 0, 0, 0, 191, 192, 1, 0, 0, 0, 192, 19, 1, 0, 0, 0, 193, 191, 1, 0, 0, 0, 194, 199, 3, 30, 15, 0, 195, 196, 5, 17, 0, 0, 196, 198, 3, 30, 15, 0, 197, 195, 1, 0, 0, 0, 198, 201, 1, 0, 0, 0, 199, 197, 1, 0, 0, 0, 199, 200, 1, 0, 0, 0, 200, 21, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, 202, 203, 3, 24, 12, 0, 203, 204, 5, 21, 0, 0, 204, 212, 3, 2, 1, 0, 205, 206, 5, 17, 0, 0, 206, 207, 3, 24, 12, 0, 207, 208, 5, 21, 0, 0, 208, 209, 3, 2, 1, 0, 209, 211, 1, 0, 0, 0, 210, 205, 1, 0, 0, 0, 211, 214, 1, 0, 0, 0, 212, 210, 1, 0, 0, 0, 212, 213, 1, 0, 0, 0, 213, 23, 1, 0, 0, 0, 214, 212, 1, 0, 0, 0, 215, 217, 5, 20, 0, 0, 216, 215, 1, 0, 0, 0, 216, 217, 1, 0, 0, 0, 217, 218, 1, 0, 0, 0, 218, 219, 3, 28, 14, 0, 219, 25, 1, 0, 0, 0, 220, 221, 3, 30, 15, 0, 221, 222, 5, 21, 0, 0, 222, 230, 3, 2, 1, 0, 223, 224, 5, 17, 0, 0, 224, 225, 3, 30, 15, 0, 225, 226, 5, 21, 0, 0, 226, 227, 3, 2, 1, 0, 227, 229, 1, 0, 0, 0, 228, 223, 1, 0, 0, 0, 229, 232, 1, 0, 0, 0, 230, 228, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 27, 1, 0, 0, 0, 232, 230, 1, 0, 0, 0, 233, 236, 5, 36, 0, 0, 234, 236, 5, 37, 0, 0, 235, 233, 1, 0, 0, 0, 235, 234, 1, 0, 0, 0, 236, 29, 1, 0, 0, 0, 237, 239, 5, 20, 0, 0, 238, 237, 1, 0, 0, 0, 238, 239, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 241, 3, 2, 1, 0, 241, 31, 1, 0, 0, 0, 242, 244, 5, 18, 0, 0, 243, 242, 1, 0, 0, 0, 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, 0, 0, 245, 257, 5, 32, 0, 0, 246, 257, 5, 33, 0, 0, 247, 249, 5, 18, 0, 0, 248, 247, 1, 0, 0, 0, 248, 249, 1, 0, 0, 0, 249, 250, 1, 0, 0, 0, 250, 257, 5, 31, 0, 0, 251, 257, 5, 34, 0, 0, 252, 257, 5, 35, 0, 0, 253, 257, 5, 26, 0, 0, 254, 257, 5, 27, 0, 0, 255, 257, 5, 28, 0, 0, 256, 243, 1, 0, 0, 0, 256, 246, 1, 0, 0, 0, 256, 248, 1, 0, 0, 0, 256, 251, 1, 0, 0, 0, 256, 252, 1, 0, 0, 0, 256, 253, 1, 0, 0, 0, 256, 254, 1, 0, 0, 0, 256, 255, 1, 0, 0, 0, 257, 33, 1, 0, 0, 0, 36, 43, 50, 58, 69, 81, 83, 90, 96, 99, 107, 115, 121, 126, 128, 132, 136, 141, 150, 153, 158, 161, 165, 172, 177, 180, 184, 191, 199, 212, 216, 230, 235, 238, 243, 248, 256] \ No newline at end of file diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.tokens b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.tokens index b305bdad3..aa1f5eee6 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.tokens +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/CEL.tokens @@ -34,6 +34,7 @@ NUM_UINT=33 STRING=34 BYTES=35 IDENTIFIER=36 +ESC_IDENTIFIER=37 '=='=1 '!='=2 'in'=3 diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.interp b/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.interp index 26e7f471e..162d52188 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.interp +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.interp @@ -36,6 +36,7 @@ null null null null +null token symbolic names: null @@ -75,6 +76,7 @@ NUM_UINT STRING BYTES IDENTIFIER +ESC_IDENTIFIER rule names: EQUALS @@ -124,6 +126,7 @@ NUM_UINT STRING BYTES IDENTIFIER +ESC_IDENTIFIER channel names: DEFAULT_TOKEN_CHANNEL @@ -133,4 +136,4 @@ mode names: DEFAULT_MODE atn: -[4, 0, 36, 423, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 17, 1, 17, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, 1, 30, 1, 30, 1, 31, 1, 31, 3, 31, 177, 8, 31, 1, 31, 4, 31, 180, 8, 31, 11, 31, 12, 31, 181, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 34, 1, 34, 3, 34, 192, 8, 34, 1, 35, 1, 35, 1, 35, 1, 36, 1, 36, 1, 36, 1, 36, 1, 36, 1, 37, 1, 37, 1, 37, 1, 37, 1, 37, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 3, 38, 225, 8, 38, 1, 39, 4, 39, 228, 8, 39, 11, 39, 12, 39, 229, 1, 39, 1, 39, 1, 40, 1, 40, 1, 40, 1, 40, 5, 40, 238, 8, 40, 10, 40, 12, 40, 241, 9, 40, 1, 40, 1, 40, 1, 41, 4, 41, 246, 8, 41, 11, 41, 12, 41, 247, 1, 41, 1, 41, 4, 41, 252, 8, 41, 11, 41, 12, 41, 253, 1, 41, 3, 41, 257, 8, 41, 1, 41, 4, 41, 260, 8, 41, 11, 41, 12, 41, 261, 1, 41, 1, 41, 1, 41, 1, 41, 4, 41, 268, 8, 41, 11, 41, 12, 41, 269, 1, 41, 3, 41, 273, 8, 41, 3, 41, 275, 8, 41, 1, 42, 4, 42, 278, 8, 42, 11, 42, 12, 42, 279, 1, 42, 1, 42, 1, 42, 1, 42, 4, 42, 286, 8, 42, 11, 42, 12, 42, 287, 3, 42, 290, 8, 42, 1, 43, 4, 43, 293, 8, 43, 11, 43, 12, 43, 294, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 4, 43, 303, 8, 43, 11, 43, 12, 43, 304, 1, 43, 1, 43, 3, 43, 309, 8, 43, 1, 44, 1, 44, 1, 44, 5, 44, 314, 8, 44, 10, 44, 12, 44, 317, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 323, 8, 44, 10, 44, 12, 44, 326, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 335, 8, 44, 10, 44, 12, 44, 338, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 349, 8, 44, 10, 44, 12, 44, 352, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 360, 8, 44, 10, 44, 12, 44, 363, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 370, 8, 44, 10, 44, 12, 44, 373, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 383, 8, 44, 10, 44, 12, 44, 386, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 398, 8, 44, 10, 44, 12, 44, 401, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 3, 44, 407, 8, 44, 1, 45, 1, 45, 1, 45, 1, 46, 1, 46, 3, 46, 414, 8, 46, 1, 46, 1, 46, 1, 46, 5, 46, 419, 8, 46, 10, 46, 12, 46, 422, 9, 46, 4, 336, 350, 384, 399, 0, 47, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 21, 11, 23, 12, 25, 13, 27, 14, 29, 15, 31, 16, 33, 17, 35, 18, 37, 19, 39, 20, 41, 21, 43, 22, 45, 23, 47, 24, 49, 25, 51, 26, 53, 27, 55, 28, 57, 0, 59, 0, 61, 0, 63, 0, 65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, 0, 79, 29, 81, 30, 83, 31, 85, 32, 87, 33, 89, 34, 91, 35, 93, 36, 1, 0, 16, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 10, 12, 13, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, 456, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 21, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0, 0, 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, 0, 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 0, 43, 1, 0, 0, 0, 0, 45, 1, 0, 0, 0, 0, 47, 1, 0, 0, 0, 0, 49, 1, 0, 0, 0, 0, 51, 1, 0, 0, 0, 0, 53, 1, 0, 0, 0, 0, 55, 1, 0, 0, 0, 0, 79, 1, 0, 0, 0, 0, 81, 1, 0, 0, 0, 0, 83, 1, 0, 0, 0, 0, 85, 1, 0, 0, 0, 0, 87, 1, 0, 0, 0, 0, 89, 1, 0, 0, 0, 0, 91, 1, 0, 0, 0, 0, 93, 1, 0, 0, 0, 1, 95, 1, 0, 0, 0, 3, 98, 1, 0, 0, 0, 5, 101, 1, 0, 0, 0, 7, 104, 1, 0, 0, 0, 9, 106, 1, 0, 0, 0, 11, 109, 1, 0, 0, 0, 13, 112, 1, 0, 0, 0, 15, 114, 1, 0, 0, 0, 17, 117, 1, 0, 0, 0, 19, 120, 1, 0, 0, 0, 21, 122, 1, 0, 0, 0, 23, 124, 1, 0, 0, 0, 25, 126, 1, 0, 0, 0, 27, 128, 1, 0, 0, 0, 29, 130, 1, 0, 0, 0, 31, 132, 1, 0, 0, 0, 33, 134, 1, 0, 0, 0, 35, 136, 1, 0, 0, 0, 37, 138, 1, 0, 0, 0, 39, 140, 1, 0, 0, 0, 41, 142, 1, 0, 0, 0, 43, 144, 1, 0, 0, 0, 45, 146, 1, 0, 0, 0, 47, 148, 1, 0, 0, 0, 49, 150, 1, 0, 0, 0, 51, 152, 1, 0, 0, 0, 53, 157, 1, 0, 0, 0, 55, 163, 1, 0, 0, 0, 57, 168, 1, 0, 0, 0, 59, 170, 1, 0, 0, 0, 61, 172, 1, 0, 0, 0, 63, 174, 1, 0, 0, 0, 65, 183, 1, 0, 0, 0, 67, 185, 1, 0, 0, 0, 69, 191, 1, 0, 0, 0, 71, 193, 1, 0, 0, 0, 73, 196, 1, 0, 0, 0, 75, 201, 1, 0, 0, 0, 77, 224, 1, 0, 0, 0, 79, 227, 1, 0, 0, 0, 81, 233, 1, 0, 0, 0, 83, 274, 1, 0, 0, 0, 85, 289, 1, 0, 0, 0, 87, 308, 1, 0, 0, 0, 89, 406, 1, 0, 0, 0, 91, 408, 1, 0, 0, 0, 93, 413, 1, 0, 0, 0, 95, 96, 5, 61, 0, 0, 96, 97, 5, 61, 0, 0, 97, 2, 1, 0, 0, 0, 98, 99, 5, 33, 0, 0, 99, 100, 5, 61, 0, 0, 100, 4, 1, 0, 0, 0, 101, 102, 5, 105, 0, 0, 102, 103, 5, 110, 0, 0, 103, 6, 1, 0, 0, 0, 104, 105, 5, 60, 0, 0, 105, 8, 1, 0, 0, 0, 106, 107, 5, 60, 0, 0, 107, 108, 5, 61, 0, 0, 108, 10, 1, 0, 0, 0, 109, 110, 5, 62, 0, 0, 110, 111, 5, 61, 0, 0, 111, 12, 1, 0, 0, 0, 112, 113, 5, 62, 0, 0, 113, 14, 1, 0, 0, 0, 114, 115, 5, 38, 0, 0, 115, 116, 5, 38, 0, 0, 116, 16, 1, 0, 0, 0, 117, 118, 5, 124, 0, 0, 118, 119, 5, 124, 0, 0, 119, 18, 1, 0, 0, 0, 120, 121, 5, 91, 0, 0, 121, 20, 1, 0, 0, 0, 122, 123, 5, 93, 0, 0, 123, 22, 1, 0, 0, 0, 124, 125, 5, 123, 0, 0, 125, 24, 1, 0, 0, 0, 126, 127, 5, 125, 0, 0, 127, 26, 1, 0, 0, 0, 128, 129, 5, 40, 0, 0, 129, 28, 1, 0, 0, 0, 130, 131, 5, 41, 0, 0, 131, 30, 1, 0, 0, 0, 132, 133, 5, 46, 0, 0, 133, 32, 1, 0, 0, 0, 134, 135, 5, 44, 0, 0, 135, 34, 1, 0, 0, 0, 136, 137, 5, 45, 0, 0, 137, 36, 1, 0, 0, 0, 138, 139, 5, 33, 0, 0, 139, 38, 1, 0, 0, 0, 140, 141, 5, 63, 0, 0, 141, 40, 1, 0, 0, 0, 142, 143, 5, 58, 0, 0, 143, 42, 1, 0, 0, 0, 144, 145, 5, 43, 0, 0, 145, 44, 1, 0, 0, 0, 146, 147, 5, 42, 0, 0, 147, 46, 1, 0, 0, 0, 148, 149, 5, 47, 0, 0, 149, 48, 1, 0, 0, 0, 150, 151, 5, 37, 0, 0, 151, 50, 1, 0, 0, 0, 152, 153, 5, 116, 0, 0, 153, 154, 5, 114, 0, 0, 154, 155, 5, 117, 0, 0, 155, 156, 5, 101, 0, 0, 156, 52, 1, 0, 0, 0, 157, 158, 5, 102, 0, 0, 158, 159, 5, 97, 0, 0, 159, 160, 5, 108, 0, 0, 160, 161, 5, 115, 0, 0, 161, 162, 5, 101, 0, 0, 162, 54, 1, 0, 0, 0, 163, 164, 5, 110, 0, 0, 164, 165, 5, 117, 0, 0, 165, 166, 5, 108, 0, 0, 166, 167, 5, 108, 0, 0, 167, 56, 1, 0, 0, 0, 168, 169, 5, 92, 0, 0, 169, 58, 1, 0, 0, 0, 170, 171, 7, 0, 0, 0, 171, 60, 1, 0, 0, 0, 172, 173, 2, 48, 57, 0, 173, 62, 1, 0, 0, 0, 174, 176, 7, 1, 0, 0, 175, 177, 7, 2, 0, 0, 176, 175, 1, 0, 0, 0, 176, 177, 1, 0, 0, 0, 177, 179, 1, 0, 0, 0, 178, 180, 3, 61, 30, 0, 179, 178, 1, 0, 0, 0, 180, 181, 1, 0, 0, 0, 181, 179, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 64, 1, 0, 0, 0, 183, 184, 7, 3, 0, 0, 184, 66, 1, 0, 0, 0, 185, 186, 7, 4, 0, 0, 186, 68, 1, 0, 0, 0, 187, 192, 3, 71, 35, 0, 188, 192, 3, 75, 37, 0, 189, 192, 3, 77, 38, 0, 190, 192, 3, 73, 36, 0, 191, 187, 1, 0, 0, 0, 191, 188, 1, 0, 0, 0, 191, 189, 1, 0, 0, 0, 191, 190, 1, 0, 0, 0, 192, 70, 1, 0, 0, 0, 193, 194, 3, 57, 28, 0, 194, 195, 7, 5, 0, 0, 195, 72, 1, 0, 0, 0, 196, 197, 3, 57, 28, 0, 197, 198, 2, 48, 51, 0, 198, 199, 2, 48, 55, 0, 199, 200, 2, 48, 55, 0, 200, 74, 1, 0, 0, 0, 201, 202, 3, 57, 28, 0, 202, 203, 7, 6, 0, 0, 203, 204, 3, 65, 32, 0, 204, 205, 3, 65, 32, 0, 205, 76, 1, 0, 0, 0, 206, 207, 3, 57, 28, 0, 207, 208, 5, 117, 0, 0, 208, 209, 3, 65, 32, 0, 209, 210, 3, 65, 32, 0, 210, 211, 3, 65, 32, 0, 211, 212, 3, 65, 32, 0, 212, 225, 1, 0, 0, 0, 213, 214, 3, 57, 28, 0, 214, 215, 5, 85, 0, 0, 215, 216, 3, 65, 32, 0, 216, 217, 3, 65, 32, 0, 217, 218, 3, 65, 32, 0, 218, 219, 3, 65, 32, 0, 219, 220, 3, 65, 32, 0, 220, 221, 3, 65, 32, 0, 221, 222, 3, 65, 32, 0, 222, 223, 3, 65, 32, 0, 223, 225, 1, 0, 0, 0, 224, 206, 1, 0, 0, 0, 224, 213, 1, 0, 0, 0, 225, 78, 1, 0, 0, 0, 226, 228, 7, 7, 0, 0, 227, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 227, 1, 0, 0, 0, 229, 230, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 232, 6, 39, 0, 0, 232, 80, 1, 0, 0, 0, 233, 234, 5, 47, 0, 0, 234, 235, 5, 47, 0, 0, 235, 239, 1, 0, 0, 0, 236, 238, 8, 8, 0, 0, 237, 236, 1, 0, 0, 0, 238, 241, 1, 0, 0, 0, 239, 237, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 242, 1, 0, 0, 0, 241, 239, 1, 0, 0, 0, 242, 243, 6, 40, 0, 0, 243, 82, 1, 0, 0, 0, 244, 246, 3, 61, 30, 0, 245, 244, 1, 0, 0, 0, 246, 247, 1, 0, 0, 0, 247, 245, 1, 0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 249, 1, 0, 0, 0, 249, 251, 5, 46, 0, 0, 250, 252, 3, 61, 30, 0, 251, 250, 1, 0, 0, 0, 252, 253, 1, 0, 0, 0, 253, 251, 1, 0, 0, 0, 253, 254, 1, 0, 0, 0, 254, 256, 1, 0, 0, 0, 255, 257, 3, 63, 31, 0, 256, 255, 1, 0, 0, 0, 256, 257, 1, 0, 0, 0, 257, 275, 1, 0, 0, 0, 258, 260, 3, 61, 30, 0, 259, 258, 1, 0, 0, 0, 260, 261, 1, 0, 0, 0, 261, 259, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 263, 1, 0, 0, 0, 263, 264, 3, 63, 31, 0, 264, 275, 1, 0, 0, 0, 265, 267, 5, 46, 0, 0, 266, 268, 3, 61, 30, 0, 267, 266, 1, 0, 0, 0, 268, 269, 1, 0, 0, 0, 269, 267, 1, 0, 0, 0, 269, 270, 1, 0, 0, 0, 270, 272, 1, 0, 0, 0, 271, 273, 3, 63, 31, 0, 272, 271, 1, 0, 0, 0, 272, 273, 1, 0, 0, 0, 273, 275, 1, 0, 0, 0, 274, 245, 1, 0, 0, 0, 274, 259, 1, 0, 0, 0, 274, 265, 1, 0, 0, 0, 275, 84, 1, 0, 0, 0, 276, 278, 3, 61, 30, 0, 277, 276, 1, 0, 0, 0, 278, 279, 1, 0, 0, 0, 279, 277, 1, 0, 0, 0, 279, 280, 1, 0, 0, 0, 280, 290, 1, 0, 0, 0, 281, 282, 5, 48, 0, 0, 282, 283, 5, 120, 0, 0, 283, 285, 1, 0, 0, 0, 284, 286, 3, 65, 32, 0, 285, 284, 1, 0, 0, 0, 286, 287, 1, 0, 0, 0, 287, 285, 1, 0, 0, 0, 287, 288, 1, 0, 0, 0, 288, 290, 1, 0, 0, 0, 289, 277, 1, 0, 0, 0, 289, 281, 1, 0, 0, 0, 290, 86, 1, 0, 0, 0, 291, 293, 3, 61, 30, 0, 292, 291, 1, 0, 0, 0, 293, 294, 1, 0, 0, 0, 294, 292, 1, 0, 0, 0, 294, 295, 1, 0, 0, 0, 295, 296, 1, 0, 0, 0, 296, 297, 7, 9, 0, 0, 297, 309, 1, 0, 0, 0, 298, 299, 5, 48, 0, 0, 299, 300, 5, 120, 0, 0, 300, 302, 1, 0, 0, 0, 301, 303, 3, 65, 32, 0, 302, 301, 1, 0, 0, 0, 303, 304, 1, 0, 0, 0, 304, 302, 1, 0, 0, 0, 304, 305, 1, 0, 0, 0, 305, 306, 1, 0, 0, 0, 306, 307, 7, 9, 0, 0, 307, 309, 1, 0, 0, 0, 308, 292, 1, 0, 0, 0, 308, 298, 1, 0, 0, 0, 309, 88, 1, 0, 0, 0, 310, 315, 5, 34, 0, 0, 311, 314, 3, 69, 34, 0, 312, 314, 8, 10, 0, 0, 313, 311, 1, 0, 0, 0, 313, 312, 1, 0, 0, 0, 314, 317, 1, 0, 0, 0, 315, 313, 1, 0, 0, 0, 315, 316, 1, 0, 0, 0, 316, 318, 1, 0, 0, 0, 317, 315, 1, 0, 0, 0, 318, 407, 5, 34, 0, 0, 319, 324, 5, 39, 0, 0, 320, 323, 3, 69, 34, 0, 321, 323, 8, 11, 0, 0, 322, 320, 1, 0, 0, 0, 322, 321, 1, 0, 0, 0, 323, 326, 1, 0, 0, 0, 324, 322, 1, 0, 0, 0, 324, 325, 1, 0, 0, 0, 325, 327, 1, 0, 0, 0, 326, 324, 1, 0, 0, 0, 327, 407, 5, 39, 0, 0, 328, 329, 5, 34, 0, 0, 329, 330, 5, 34, 0, 0, 330, 331, 5, 34, 0, 0, 331, 336, 1, 0, 0, 0, 332, 335, 3, 69, 34, 0, 333, 335, 8, 12, 0, 0, 334, 332, 1, 0, 0, 0, 334, 333, 1, 0, 0, 0, 335, 338, 1, 0, 0, 0, 336, 337, 1, 0, 0, 0, 336, 334, 1, 0, 0, 0, 337, 339, 1, 0, 0, 0, 338, 336, 1, 0, 0, 0, 339, 340, 5, 34, 0, 0, 340, 341, 5, 34, 0, 0, 341, 407, 5, 34, 0, 0, 342, 343, 5, 39, 0, 0, 343, 344, 5, 39, 0, 0, 344, 345, 5, 39, 0, 0, 345, 350, 1, 0, 0, 0, 346, 349, 3, 69, 34, 0, 347, 349, 8, 12, 0, 0, 348, 346, 1, 0, 0, 0, 348, 347, 1, 0, 0, 0, 349, 352, 1, 0, 0, 0, 350, 351, 1, 0, 0, 0, 350, 348, 1, 0, 0, 0, 351, 353, 1, 0, 0, 0, 352, 350, 1, 0, 0, 0, 353, 354, 5, 39, 0, 0, 354, 355, 5, 39, 0, 0, 355, 407, 5, 39, 0, 0, 356, 357, 3, 67, 33, 0, 357, 361, 5, 34, 0, 0, 358, 360, 8, 13, 0, 0, 359, 358, 1, 0, 0, 0, 360, 363, 1, 0, 0, 0, 361, 359, 1, 0, 0, 0, 361, 362, 1, 0, 0, 0, 362, 364, 1, 0, 0, 0, 363, 361, 1, 0, 0, 0, 364, 365, 5, 34, 0, 0, 365, 407, 1, 0, 0, 0, 366, 367, 3, 67, 33, 0, 367, 371, 5, 39, 0, 0, 368, 370, 8, 14, 0, 0, 369, 368, 1, 0, 0, 0, 370, 373, 1, 0, 0, 0, 371, 369, 1, 0, 0, 0, 371, 372, 1, 0, 0, 0, 372, 374, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 374, 375, 5, 39, 0, 0, 375, 407, 1, 0, 0, 0, 376, 377, 3, 67, 33, 0, 377, 378, 5, 34, 0, 0, 378, 379, 5, 34, 0, 0, 379, 380, 5, 34, 0, 0, 380, 384, 1, 0, 0, 0, 381, 383, 9, 0, 0, 0, 382, 381, 1, 0, 0, 0, 383, 386, 1, 0, 0, 0, 384, 385, 1, 0, 0, 0, 384, 382, 1, 0, 0, 0, 385, 387, 1, 0, 0, 0, 386, 384, 1, 0, 0, 0, 387, 388, 5, 34, 0, 0, 388, 389, 5, 34, 0, 0, 389, 390, 5, 34, 0, 0, 390, 407, 1, 0, 0, 0, 391, 392, 3, 67, 33, 0, 392, 393, 5, 39, 0, 0, 393, 394, 5, 39, 0, 0, 394, 395, 5, 39, 0, 0, 395, 399, 1, 0, 0, 0, 396, 398, 9, 0, 0, 0, 397, 396, 1, 0, 0, 0, 398, 401, 1, 0, 0, 0, 399, 400, 1, 0, 0, 0, 399, 397, 1, 0, 0, 0, 400, 402, 1, 0, 0, 0, 401, 399, 1, 0, 0, 0, 402, 403, 5, 39, 0, 0, 403, 404, 5, 39, 0, 0, 404, 405, 5, 39, 0, 0, 405, 407, 1, 0, 0, 0, 406, 310, 1, 0, 0, 0, 406, 319, 1, 0, 0, 0, 406, 328, 1, 0, 0, 0, 406, 342, 1, 0, 0, 0, 406, 356, 1, 0, 0, 0, 406, 366, 1, 0, 0, 0, 406, 376, 1, 0, 0, 0, 406, 391, 1, 0, 0, 0, 407, 90, 1, 0, 0, 0, 408, 409, 7, 15, 0, 0, 409, 410, 3, 89, 44, 0, 410, 92, 1, 0, 0, 0, 411, 414, 3, 59, 29, 0, 412, 414, 5, 95, 0, 0, 413, 411, 1, 0, 0, 0, 413, 412, 1, 0, 0, 0, 414, 420, 1, 0, 0, 0, 415, 419, 3, 59, 29, 0, 416, 419, 3, 61, 30, 0, 417, 419, 5, 95, 0, 0, 418, 415, 1, 0, 0, 0, 418, 416, 1, 0, 0, 0, 418, 417, 1, 0, 0, 0, 419, 422, 1, 0, 0, 0, 420, 418, 1, 0, 0, 0, 420, 421, 1, 0, 0, 0, 421, 94, 1, 0, 0, 0, 422, 420, 1, 0, 0, 0, 36, 0, 176, 181, 191, 224, 229, 239, 247, 253, 256, 261, 269, 272, 274, 279, 287, 289, 294, 304, 308, 313, 315, 322, 324, 334, 336, 348, 350, 361, 371, 384, 399, 406, 413, 418, 420, 1, 0, 1, 0] \ No newline at end of file +[4, 0, 37, 435, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, 2, 47, 7, 47, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 17, 1, 17, 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, 1, 30, 1, 30, 1, 31, 1, 31, 3, 31, 179, 8, 31, 1, 31, 4, 31, 182, 8, 31, 11, 31, 12, 31, 183, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 34, 1, 34, 3, 34, 194, 8, 34, 1, 35, 1, 35, 1, 35, 1, 36, 1, 36, 1, 36, 1, 36, 1, 36, 1, 37, 1, 37, 1, 37, 1, 37, 1, 37, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 3, 38, 227, 8, 38, 1, 39, 4, 39, 230, 8, 39, 11, 39, 12, 39, 231, 1, 39, 1, 39, 1, 40, 1, 40, 1, 40, 1, 40, 5, 40, 240, 8, 40, 10, 40, 12, 40, 243, 9, 40, 1, 40, 1, 40, 1, 41, 4, 41, 248, 8, 41, 11, 41, 12, 41, 249, 1, 41, 1, 41, 4, 41, 254, 8, 41, 11, 41, 12, 41, 255, 1, 41, 3, 41, 259, 8, 41, 1, 41, 4, 41, 262, 8, 41, 11, 41, 12, 41, 263, 1, 41, 1, 41, 1, 41, 1, 41, 4, 41, 270, 8, 41, 11, 41, 12, 41, 271, 1, 41, 3, 41, 275, 8, 41, 3, 41, 277, 8, 41, 1, 42, 4, 42, 280, 8, 42, 11, 42, 12, 42, 281, 1, 42, 1, 42, 1, 42, 1, 42, 4, 42, 288, 8, 42, 11, 42, 12, 42, 289, 3, 42, 292, 8, 42, 1, 43, 4, 43, 295, 8, 43, 11, 43, 12, 43, 296, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 4, 43, 305, 8, 43, 11, 43, 12, 43, 306, 1, 43, 1, 43, 3, 43, 311, 8, 43, 1, 44, 1, 44, 1, 44, 5, 44, 316, 8, 44, 10, 44, 12, 44, 319, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 325, 8, 44, 10, 44, 12, 44, 328, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 337, 8, 44, 10, 44, 12, 44, 340, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 351, 8, 44, 10, 44, 12, 44, 354, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 362, 8, 44, 10, 44, 12, 44, 365, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 372, 8, 44, 10, 44, 12, 44, 375, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 385, 8, 44, 10, 44, 12, 44, 388, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 400, 8, 44, 10, 44, 12, 44, 403, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 3, 44, 409, 8, 44, 1, 45, 1, 45, 1, 45, 1, 46, 1, 46, 3, 46, 416, 8, 46, 1, 46, 1, 46, 1, 46, 5, 46, 421, 8, 46, 10, 46, 12, 46, 424, 9, 46, 1, 47, 1, 47, 1, 47, 1, 47, 4, 47, 430, 8, 47, 11, 47, 12, 47, 431, 1, 47, 1, 47, 4, 338, 352, 386, 401, 0, 48, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 21, 11, 23, 12, 25, 13, 27, 14, 29, 15, 31, 16, 33, 17, 35, 18, 37, 19, 39, 20, 41, 21, 43, 22, 45, 23, 47, 24, 49, 25, 51, 26, 53, 27, 55, 28, 57, 0, 59, 0, 61, 0, 63, 0, 65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, 0, 79, 29, 81, 30, 83, 31, 85, 32, 87, 33, 89, 34, 91, 35, 93, 36, 95, 37, 1, 0, 17, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 10, 12, 13, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, 3, 0, 32, 32, 45, 47, 95, 95, 471, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 21, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0, 0, 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, 0, 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 0, 43, 1, 0, 0, 0, 0, 45, 1, 0, 0, 0, 0, 47, 1, 0, 0, 0, 0, 49, 1, 0, 0, 0, 0, 51, 1, 0, 0, 0, 0, 53, 1, 0, 0, 0, 0, 55, 1, 0, 0, 0, 0, 79, 1, 0, 0, 0, 0, 81, 1, 0, 0, 0, 0, 83, 1, 0, 0, 0, 0, 85, 1, 0, 0, 0, 0, 87, 1, 0, 0, 0, 0, 89, 1, 0, 0, 0, 0, 91, 1, 0, 0, 0, 0, 93, 1, 0, 0, 0, 0, 95, 1, 0, 0, 0, 1, 97, 1, 0, 0, 0, 3, 100, 1, 0, 0, 0, 5, 103, 1, 0, 0, 0, 7, 106, 1, 0, 0, 0, 9, 108, 1, 0, 0, 0, 11, 111, 1, 0, 0, 0, 13, 114, 1, 0, 0, 0, 15, 116, 1, 0, 0, 0, 17, 119, 1, 0, 0, 0, 19, 122, 1, 0, 0, 0, 21, 124, 1, 0, 0, 0, 23, 126, 1, 0, 0, 0, 25, 128, 1, 0, 0, 0, 27, 130, 1, 0, 0, 0, 29, 132, 1, 0, 0, 0, 31, 134, 1, 0, 0, 0, 33, 136, 1, 0, 0, 0, 35, 138, 1, 0, 0, 0, 37, 140, 1, 0, 0, 0, 39, 142, 1, 0, 0, 0, 41, 144, 1, 0, 0, 0, 43, 146, 1, 0, 0, 0, 45, 148, 1, 0, 0, 0, 47, 150, 1, 0, 0, 0, 49, 152, 1, 0, 0, 0, 51, 154, 1, 0, 0, 0, 53, 159, 1, 0, 0, 0, 55, 165, 1, 0, 0, 0, 57, 170, 1, 0, 0, 0, 59, 172, 1, 0, 0, 0, 61, 174, 1, 0, 0, 0, 63, 176, 1, 0, 0, 0, 65, 185, 1, 0, 0, 0, 67, 187, 1, 0, 0, 0, 69, 193, 1, 0, 0, 0, 71, 195, 1, 0, 0, 0, 73, 198, 1, 0, 0, 0, 75, 203, 1, 0, 0, 0, 77, 226, 1, 0, 0, 0, 79, 229, 1, 0, 0, 0, 81, 235, 1, 0, 0, 0, 83, 276, 1, 0, 0, 0, 85, 291, 1, 0, 0, 0, 87, 310, 1, 0, 0, 0, 89, 408, 1, 0, 0, 0, 91, 410, 1, 0, 0, 0, 93, 415, 1, 0, 0, 0, 95, 425, 1, 0, 0, 0, 97, 98, 5, 61, 0, 0, 98, 99, 5, 61, 0, 0, 99, 2, 1, 0, 0, 0, 100, 101, 5, 33, 0, 0, 101, 102, 5, 61, 0, 0, 102, 4, 1, 0, 0, 0, 103, 104, 5, 105, 0, 0, 104, 105, 5, 110, 0, 0, 105, 6, 1, 0, 0, 0, 106, 107, 5, 60, 0, 0, 107, 8, 1, 0, 0, 0, 108, 109, 5, 60, 0, 0, 109, 110, 5, 61, 0, 0, 110, 10, 1, 0, 0, 0, 111, 112, 5, 62, 0, 0, 112, 113, 5, 61, 0, 0, 113, 12, 1, 0, 0, 0, 114, 115, 5, 62, 0, 0, 115, 14, 1, 0, 0, 0, 116, 117, 5, 38, 0, 0, 117, 118, 5, 38, 0, 0, 118, 16, 1, 0, 0, 0, 119, 120, 5, 124, 0, 0, 120, 121, 5, 124, 0, 0, 121, 18, 1, 0, 0, 0, 122, 123, 5, 91, 0, 0, 123, 20, 1, 0, 0, 0, 124, 125, 5, 93, 0, 0, 125, 22, 1, 0, 0, 0, 126, 127, 5, 123, 0, 0, 127, 24, 1, 0, 0, 0, 128, 129, 5, 125, 0, 0, 129, 26, 1, 0, 0, 0, 130, 131, 5, 40, 0, 0, 131, 28, 1, 0, 0, 0, 132, 133, 5, 41, 0, 0, 133, 30, 1, 0, 0, 0, 134, 135, 5, 46, 0, 0, 135, 32, 1, 0, 0, 0, 136, 137, 5, 44, 0, 0, 137, 34, 1, 0, 0, 0, 138, 139, 5, 45, 0, 0, 139, 36, 1, 0, 0, 0, 140, 141, 5, 33, 0, 0, 141, 38, 1, 0, 0, 0, 142, 143, 5, 63, 0, 0, 143, 40, 1, 0, 0, 0, 144, 145, 5, 58, 0, 0, 145, 42, 1, 0, 0, 0, 146, 147, 5, 43, 0, 0, 147, 44, 1, 0, 0, 0, 148, 149, 5, 42, 0, 0, 149, 46, 1, 0, 0, 0, 150, 151, 5, 47, 0, 0, 151, 48, 1, 0, 0, 0, 152, 153, 5, 37, 0, 0, 153, 50, 1, 0, 0, 0, 154, 155, 5, 116, 0, 0, 155, 156, 5, 114, 0, 0, 156, 157, 5, 117, 0, 0, 157, 158, 5, 101, 0, 0, 158, 52, 1, 0, 0, 0, 159, 160, 5, 102, 0, 0, 160, 161, 5, 97, 0, 0, 161, 162, 5, 108, 0, 0, 162, 163, 5, 115, 0, 0, 163, 164, 5, 101, 0, 0, 164, 54, 1, 0, 0, 0, 165, 166, 5, 110, 0, 0, 166, 167, 5, 117, 0, 0, 167, 168, 5, 108, 0, 0, 168, 169, 5, 108, 0, 0, 169, 56, 1, 0, 0, 0, 170, 171, 5, 92, 0, 0, 171, 58, 1, 0, 0, 0, 172, 173, 7, 0, 0, 0, 173, 60, 1, 0, 0, 0, 174, 175, 2, 48, 57, 0, 175, 62, 1, 0, 0, 0, 176, 178, 7, 1, 0, 0, 177, 179, 7, 2, 0, 0, 178, 177, 1, 0, 0, 0, 178, 179, 1, 0, 0, 0, 179, 181, 1, 0, 0, 0, 180, 182, 3, 61, 30, 0, 181, 180, 1, 0, 0, 0, 182, 183, 1, 0, 0, 0, 183, 181, 1, 0, 0, 0, 183, 184, 1, 0, 0, 0, 184, 64, 1, 0, 0, 0, 185, 186, 7, 3, 0, 0, 186, 66, 1, 0, 0, 0, 187, 188, 7, 4, 0, 0, 188, 68, 1, 0, 0, 0, 189, 194, 3, 71, 35, 0, 190, 194, 3, 75, 37, 0, 191, 194, 3, 77, 38, 0, 192, 194, 3, 73, 36, 0, 193, 189, 1, 0, 0, 0, 193, 190, 1, 0, 0, 0, 193, 191, 1, 0, 0, 0, 193, 192, 1, 0, 0, 0, 194, 70, 1, 0, 0, 0, 195, 196, 3, 57, 28, 0, 196, 197, 7, 5, 0, 0, 197, 72, 1, 0, 0, 0, 198, 199, 3, 57, 28, 0, 199, 200, 2, 48, 51, 0, 200, 201, 2, 48, 55, 0, 201, 202, 2, 48, 55, 0, 202, 74, 1, 0, 0, 0, 203, 204, 3, 57, 28, 0, 204, 205, 7, 6, 0, 0, 205, 206, 3, 65, 32, 0, 206, 207, 3, 65, 32, 0, 207, 76, 1, 0, 0, 0, 208, 209, 3, 57, 28, 0, 209, 210, 5, 117, 0, 0, 210, 211, 3, 65, 32, 0, 211, 212, 3, 65, 32, 0, 212, 213, 3, 65, 32, 0, 213, 214, 3, 65, 32, 0, 214, 227, 1, 0, 0, 0, 215, 216, 3, 57, 28, 0, 216, 217, 5, 85, 0, 0, 217, 218, 3, 65, 32, 0, 218, 219, 3, 65, 32, 0, 219, 220, 3, 65, 32, 0, 220, 221, 3, 65, 32, 0, 221, 222, 3, 65, 32, 0, 222, 223, 3, 65, 32, 0, 223, 224, 3, 65, 32, 0, 224, 225, 3, 65, 32, 0, 225, 227, 1, 0, 0, 0, 226, 208, 1, 0, 0, 0, 226, 215, 1, 0, 0, 0, 227, 78, 1, 0, 0, 0, 228, 230, 7, 7, 0, 0, 229, 228, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 229, 1, 0, 0, 0, 231, 232, 1, 0, 0, 0, 232, 233, 1, 0, 0, 0, 233, 234, 6, 39, 0, 0, 234, 80, 1, 0, 0, 0, 235, 236, 5, 47, 0, 0, 236, 237, 5, 47, 0, 0, 237, 241, 1, 0, 0, 0, 238, 240, 8, 8, 0, 0, 239, 238, 1, 0, 0, 0, 240, 243, 1, 0, 0, 0, 241, 239, 1, 0, 0, 0, 241, 242, 1, 0, 0, 0, 242, 244, 1, 0, 0, 0, 243, 241, 1, 0, 0, 0, 244, 245, 6, 40, 0, 0, 245, 82, 1, 0, 0, 0, 246, 248, 3, 61, 30, 0, 247, 246, 1, 0, 0, 0, 248, 249, 1, 0, 0, 0, 249, 247, 1, 0, 0, 0, 249, 250, 1, 0, 0, 0, 250, 251, 1, 0, 0, 0, 251, 253, 5, 46, 0, 0, 252, 254, 3, 61, 30, 0, 253, 252, 1, 0, 0, 0, 254, 255, 1, 0, 0, 0, 255, 253, 1, 0, 0, 0, 255, 256, 1, 0, 0, 0, 256, 258, 1, 0, 0, 0, 257, 259, 3, 63, 31, 0, 258, 257, 1, 0, 0, 0, 258, 259, 1, 0, 0, 0, 259, 277, 1, 0, 0, 0, 260, 262, 3, 61, 30, 0, 261, 260, 1, 0, 0, 0, 262, 263, 1, 0, 0, 0, 263, 261, 1, 0, 0, 0, 263, 264, 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, 265, 266, 3, 63, 31, 0, 266, 277, 1, 0, 0, 0, 267, 269, 5, 46, 0, 0, 268, 270, 3, 61, 30, 0, 269, 268, 1, 0, 0, 0, 270, 271, 1, 0, 0, 0, 271, 269, 1, 0, 0, 0, 271, 272, 1, 0, 0, 0, 272, 274, 1, 0, 0, 0, 273, 275, 3, 63, 31, 0, 274, 273, 1, 0, 0, 0, 274, 275, 1, 0, 0, 0, 275, 277, 1, 0, 0, 0, 276, 247, 1, 0, 0, 0, 276, 261, 1, 0, 0, 0, 276, 267, 1, 0, 0, 0, 277, 84, 1, 0, 0, 0, 278, 280, 3, 61, 30, 0, 279, 278, 1, 0, 0, 0, 280, 281, 1, 0, 0, 0, 281, 279, 1, 0, 0, 0, 281, 282, 1, 0, 0, 0, 282, 292, 1, 0, 0, 0, 283, 284, 5, 48, 0, 0, 284, 285, 5, 120, 0, 0, 285, 287, 1, 0, 0, 0, 286, 288, 3, 65, 32, 0, 287, 286, 1, 0, 0, 0, 288, 289, 1, 0, 0, 0, 289, 287, 1, 0, 0, 0, 289, 290, 1, 0, 0, 0, 290, 292, 1, 0, 0, 0, 291, 279, 1, 0, 0, 0, 291, 283, 1, 0, 0, 0, 292, 86, 1, 0, 0, 0, 293, 295, 3, 61, 30, 0, 294, 293, 1, 0, 0, 0, 295, 296, 1, 0, 0, 0, 296, 294, 1, 0, 0, 0, 296, 297, 1, 0, 0, 0, 297, 298, 1, 0, 0, 0, 298, 299, 7, 9, 0, 0, 299, 311, 1, 0, 0, 0, 300, 301, 5, 48, 0, 0, 301, 302, 5, 120, 0, 0, 302, 304, 1, 0, 0, 0, 303, 305, 3, 65, 32, 0, 304, 303, 1, 0, 0, 0, 305, 306, 1, 0, 0, 0, 306, 304, 1, 0, 0, 0, 306, 307, 1, 0, 0, 0, 307, 308, 1, 0, 0, 0, 308, 309, 7, 9, 0, 0, 309, 311, 1, 0, 0, 0, 310, 294, 1, 0, 0, 0, 310, 300, 1, 0, 0, 0, 311, 88, 1, 0, 0, 0, 312, 317, 5, 34, 0, 0, 313, 316, 3, 69, 34, 0, 314, 316, 8, 10, 0, 0, 315, 313, 1, 0, 0, 0, 315, 314, 1, 0, 0, 0, 316, 319, 1, 0, 0, 0, 317, 315, 1, 0, 0, 0, 317, 318, 1, 0, 0, 0, 318, 320, 1, 0, 0, 0, 319, 317, 1, 0, 0, 0, 320, 409, 5, 34, 0, 0, 321, 326, 5, 39, 0, 0, 322, 325, 3, 69, 34, 0, 323, 325, 8, 11, 0, 0, 324, 322, 1, 0, 0, 0, 324, 323, 1, 0, 0, 0, 325, 328, 1, 0, 0, 0, 326, 324, 1, 0, 0, 0, 326, 327, 1, 0, 0, 0, 327, 329, 1, 0, 0, 0, 328, 326, 1, 0, 0, 0, 329, 409, 5, 39, 0, 0, 330, 331, 5, 34, 0, 0, 331, 332, 5, 34, 0, 0, 332, 333, 5, 34, 0, 0, 333, 338, 1, 0, 0, 0, 334, 337, 3, 69, 34, 0, 335, 337, 8, 12, 0, 0, 336, 334, 1, 0, 0, 0, 336, 335, 1, 0, 0, 0, 337, 340, 1, 0, 0, 0, 338, 339, 1, 0, 0, 0, 338, 336, 1, 0, 0, 0, 339, 341, 1, 0, 0, 0, 340, 338, 1, 0, 0, 0, 341, 342, 5, 34, 0, 0, 342, 343, 5, 34, 0, 0, 343, 409, 5, 34, 0, 0, 344, 345, 5, 39, 0, 0, 345, 346, 5, 39, 0, 0, 346, 347, 5, 39, 0, 0, 347, 352, 1, 0, 0, 0, 348, 351, 3, 69, 34, 0, 349, 351, 8, 12, 0, 0, 350, 348, 1, 0, 0, 0, 350, 349, 1, 0, 0, 0, 351, 354, 1, 0, 0, 0, 352, 353, 1, 0, 0, 0, 352, 350, 1, 0, 0, 0, 353, 355, 1, 0, 0, 0, 354, 352, 1, 0, 0, 0, 355, 356, 5, 39, 0, 0, 356, 357, 5, 39, 0, 0, 357, 409, 5, 39, 0, 0, 358, 359, 3, 67, 33, 0, 359, 363, 5, 34, 0, 0, 360, 362, 8, 13, 0, 0, 361, 360, 1, 0, 0, 0, 362, 365, 1, 0, 0, 0, 363, 361, 1, 0, 0, 0, 363, 364, 1, 0, 0, 0, 364, 366, 1, 0, 0, 0, 365, 363, 1, 0, 0, 0, 366, 367, 5, 34, 0, 0, 367, 409, 1, 0, 0, 0, 368, 369, 3, 67, 33, 0, 369, 373, 5, 39, 0, 0, 370, 372, 8, 14, 0, 0, 371, 370, 1, 0, 0, 0, 372, 375, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 373, 374, 1, 0, 0, 0, 374, 376, 1, 0, 0, 0, 375, 373, 1, 0, 0, 0, 376, 377, 5, 39, 0, 0, 377, 409, 1, 0, 0, 0, 378, 379, 3, 67, 33, 0, 379, 380, 5, 34, 0, 0, 380, 381, 5, 34, 0, 0, 381, 382, 5, 34, 0, 0, 382, 386, 1, 0, 0, 0, 383, 385, 9, 0, 0, 0, 384, 383, 1, 0, 0, 0, 385, 388, 1, 0, 0, 0, 386, 387, 1, 0, 0, 0, 386, 384, 1, 0, 0, 0, 387, 389, 1, 0, 0, 0, 388, 386, 1, 0, 0, 0, 389, 390, 5, 34, 0, 0, 390, 391, 5, 34, 0, 0, 391, 392, 5, 34, 0, 0, 392, 409, 1, 0, 0, 0, 393, 394, 3, 67, 33, 0, 394, 395, 5, 39, 0, 0, 395, 396, 5, 39, 0, 0, 396, 397, 5, 39, 0, 0, 397, 401, 1, 0, 0, 0, 398, 400, 9, 0, 0, 0, 399, 398, 1, 0, 0, 0, 400, 403, 1, 0, 0, 0, 401, 402, 1, 0, 0, 0, 401, 399, 1, 0, 0, 0, 402, 404, 1, 0, 0, 0, 403, 401, 1, 0, 0, 0, 404, 405, 5, 39, 0, 0, 405, 406, 5, 39, 0, 0, 406, 407, 5, 39, 0, 0, 407, 409, 1, 0, 0, 0, 408, 312, 1, 0, 0, 0, 408, 321, 1, 0, 0, 0, 408, 330, 1, 0, 0, 0, 408, 344, 1, 0, 0, 0, 408, 358, 1, 0, 0, 0, 408, 368, 1, 0, 0, 0, 408, 378, 1, 0, 0, 0, 408, 393, 1, 0, 0, 0, 409, 90, 1, 0, 0, 0, 410, 411, 7, 15, 0, 0, 411, 412, 3, 89, 44, 0, 412, 92, 1, 0, 0, 0, 413, 416, 3, 59, 29, 0, 414, 416, 5, 95, 0, 0, 415, 413, 1, 0, 0, 0, 415, 414, 1, 0, 0, 0, 416, 422, 1, 0, 0, 0, 417, 421, 3, 59, 29, 0, 418, 421, 3, 61, 30, 0, 419, 421, 5, 95, 0, 0, 420, 417, 1, 0, 0, 0, 420, 418, 1, 0, 0, 0, 420, 419, 1, 0, 0, 0, 421, 424, 1, 0, 0, 0, 422, 420, 1, 0, 0, 0, 422, 423, 1, 0, 0, 0, 423, 94, 1, 0, 0, 0, 424, 422, 1, 0, 0, 0, 425, 429, 5, 96, 0, 0, 426, 430, 3, 59, 29, 0, 427, 430, 3, 61, 30, 0, 428, 430, 7, 16, 0, 0, 429, 426, 1, 0, 0, 0, 429, 427, 1, 0, 0, 0, 429, 428, 1, 0, 0, 0, 430, 431, 1, 0, 0, 0, 431, 429, 1, 0, 0, 0, 431, 432, 1, 0, 0, 0, 432, 433, 1, 0, 0, 0, 433, 434, 5, 96, 0, 0, 434, 96, 1, 0, 0, 0, 38, 0, 178, 183, 193, 226, 231, 241, 249, 255, 258, 263, 271, 274, 276, 281, 289, 291, 296, 306, 310, 315, 317, 324, 326, 336, 338, 350, 352, 363, 373, 386, 401, 408, 415, 420, 422, 429, 431, 1, 0, 1, 0] \ No newline at end of file diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens b/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens index b305bdad3..aa1f5eee6 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/CELLexer.tokens @@ -34,6 +34,7 @@ NUM_UINT=33 STRING=34 BYTES=35 IDENTIFIER=36 +ESC_IDENTIFIER=37 '=='=1 '!='=2 'in'=3 diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go index c49d03867..514f2082f 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_listener.go @@ -1,4 +1,4 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen // CEL import "github.com/antlr4-go/antlr/v4" @@ -98,11 +98,17 @@ func (s *BaseCELListener) EnterIndex(ctx *IndexContext) {} // ExitIndex is called when production Index is exited. func (s *BaseCELListener) ExitIndex(ctx *IndexContext) {} -// EnterIdentOrGlobalCall is called when production IdentOrGlobalCall is entered. -func (s *BaseCELListener) EnterIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) {} +// EnterIdent is called when production Ident is entered. +func (s *BaseCELListener) EnterIdent(ctx *IdentContext) {} -// ExitIdentOrGlobalCall is called when production IdentOrGlobalCall is exited. -func (s *BaseCELListener) ExitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) {} +// ExitIdent is called when production Ident is exited. +func (s *BaseCELListener) ExitIdent(ctx *IdentContext) {} + +// EnterGlobalCall is called when production GlobalCall is entered. +func (s *BaseCELListener) EnterGlobalCall(ctx *GlobalCallContext) {} + +// ExitGlobalCall is called when production GlobalCall is exited. +func (s *BaseCELListener) ExitGlobalCall(ctx *GlobalCallContext) {} // EnterNested is called when production Nested is entered. func (s *BaseCELListener) EnterNested(ctx *NestedContext) {} @@ -164,6 +170,18 @@ func (s *BaseCELListener) EnterMapInitializerList(ctx *MapInitializerListContext // ExitMapInitializerList is called when production mapInitializerList is exited. func (s *BaseCELListener) ExitMapInitializerList(ctx *MapInitializerListContext) {} +// EnterSimpleIdentifier is called when production SimpleIdentifier is entered. +func (s *BaseCELListener) EnterSimpleIdentifier(ctx *SimpleIdentifierContext) {} + +// ExitSimpleIdentifier is called when production SimpleIdentifier is exited. +func (s *BaseCELListener) ExitSimpleIdentifier(ctx *SimpleIdentifierContext) {} + +// EnterEscapedIdentifier is called when production EscapedIdentifier is entered. +func (s *BaseCELListener) EnterEscapedIdentifier(ctx *EscapedIdentifierContext) {} + +// ExitEscapedIdentifier is called when production EscapedIdentifier is exited. +func (s *BaseCELListener) ExitEscapedIdentifier(ctx *EscapedIdentifierContext) {} + // EnterOptExpr is called when production optExpr is entered. func (s *BaseCELListener) EnterOptExpr(ctx *OptExprContext) {} diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go index b2c0783d3..8a12cb65e 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_base_visitor.go @@ -1,9 +1,8 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen // CEL import "github.com/antlr4-go/antlr/v4" - type BaseCELVisitor struct { *antlr.BaseParseTreeVisitor } @@ -60,7 +59,11 @@ func (v *BaseCELVisitor) VisitIndex(ctx *IndexContext) interface{} { return v.VisitChildren(ctx) } -func (v *BaseCELVisitor) VisitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) interface{} { +func (v *BaseCELVisitor) VisitIdent(ctx *IdentContext) interface{} { + return v.VisitChildren(ctx) +} + +func (v *BaseCELVisitor) VisitGlobalCall(ctx *GlobalCallContext) interface{} { return v.VisitChildren(ctx) } @@ -104,6 +107,14 @@ func (v *BaseCELVisitor) VisitMapInitializerList(ctx *MapInitializerListContext) return v.VisitChildren(ctx) } +func (v *BaseCELVisitor) VisitSimpleIdentifier(ctx *SimpleIdentifierContext) interface{} { + return v.VisitChildren(ctx) +} + +func (v *BaseCELVisitor) VisitEscapedIdentifier(ctx *EscapedIdentifierContext) interface{} { + return v.VisitChildren(ctx) +} + func (v *BaseCELVisitor) VisitOptExpr(ctx *OptExprContext) interface{} { return v.VisitChildren(ctx) } diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_lexer.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_lexer.go index e026cc46f..896562f5f 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_lexer.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_lexer.go @@ -1,278 +1,285 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen + import ( "fmt" - "sync" - "unicode" "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" ) + // Suppress unused import error var _ = fmt.Printf var _ = sync.Once{} var _ = unicode.IsLetter - type CELLexer struct { *antlr.BaseLexer channelNames []string - modeNames []string + modeNames []string // TODO: EOF string } var CELLexerLexerStaticData struct { - once sync.Once - serializedATN []int32 - ChannelNames []string - ModeNames []string - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA } func cellexerLexerInit() { - staticData := &CELLexerLexerStaticData - staticData.ChannelNames = []string{ - "DEFAULT_TOKEN_CHANNEL", "HIDDEN", - } - staticData.ModeNames = []string{ - "DEFAULT_MODE", - } - staticData.LiteralNames = []string{ - "", "'=='", "'!='", "'in'", "'<'", "'<='", "'>='", "'>'", "'&&'", "'||'", - "'['", "']'", "'{'", "'}'", "'('", "')'", "'.'", "','", "'-'", "'!'", - "'?'", "':'", "'+'", "'*'", "'/'", "'%'", "'true'", "'false'", "'null'", - } - staticData.SymbolicNames = []string{ - "", "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", - "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", - "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", - "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", - "NUL", "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", - "STRING", "BYTES", "IDENTIFIER", - } - staticData.RuleNames = []string{ - "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", - "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", - "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", - "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", - "NUL", "BACKSLASH", "LETTER", "DIGIT", "EXPONENT", "HEXDIGIT", "RAW", - "ESC_SEQ", "ESC_CHAR_SEQ", "ESC_OCT_SEQ", "ESC_BYTE_SEQ", "ESC_UNI_SEQ", - "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", "STRING", - "BYTES", "IDENTIFIER", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 0, 36, 423, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, - 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, - 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, - 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, - 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, - 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, - 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, - 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, - 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, - 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8, - 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, - 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 17, 1, 17, 1, 18, 1, 18, 1, - 19, 1, 19, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 23, 1, 23, 1, 24, - 1, 24, 1, 25, 1, 25, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 26, 1, - 26, 1, 26, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29, - 1, 30, 1, 30, 1, 31, 1, 31, 3, 31, 177, 8, 31, 1, 31, 4, 31, 180, 8, 31, - 11, 31, 12, 31, 181, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 34, 1, - 34, 3, 34, 192, 8, 34, 1, 35, 1, 35, 1, 35, 1, 36, 1, 36, 1, 36, 1, 36, - 1, 36, 1, 37, 1, 37, 1, 37, 1, 37, 1, 37, 1, 38, 1, 38, 1, 38, 1, 38, 1, - 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, - 1, 38, 1, 38, 1, 38, 3, 38, 225, 8, 38, 1, 39, 4, 39, 228, 8, 39, 11, 39, - 12, 39, 229, 1, 39, 1, 39, 1, 40, 1, 40, 1, 40, 1, 40, 5, 40, 238, 8, 40, - 10, 40, 12, 40, 241, 9, 40, 1, 40, 1, 40, 1, 41, 4, 41, 246, 8, 41, 11, - 41, 12, 41, 247, 1, 41, 1, 41, 4, 41, 252, 8, 41, 11, 41, 12, 41, 253, - 1, 41, 3, 41, 257, 8, 41, 1, 41, 4, 41, 260, 8, 41, 11, 41, 12, 41, 261, - 1, 41, 1, 41, 1, 41, 1, 41, 4, 41, 268, 8, 41, 11, 41, 12, 41, 269, 1, - 41, 3, 41, 273, 8, 41, 3, 41, 275, 8, 41, 1, 42, 4, 42, 278, 8, 42, 11, - 42, 12, 42, 279, 1, 42, 1, 42, 1, 42, 1, 42, 4, 42, 286, 8, 42, 11, 42, - 12, 42, 287, 3, 42, 290, 8, 42, 1, 43, 4, 43, 293, 8, 43, 11, 43, 12, 43, - 294, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 4, 43, 303, 8, 43, 11, 43, - 12, 43, 304, 1, 43, 1, 43, 3, 43, 309, 8, 43, 1, 44, 1, 44, 1, 44, 5, 44, - 314, 8, 44, 10, 44, 12, 44, 317, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, - 44, 323, 8, 44, 10, 44, 12, 44, 326, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, - 1, 44, 1, 44, 1, 44, 5, 44, 335, 8, 44, 10, 44, 12, 44, 338, 9, 44, 1, - 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 349, - 8, 44, 10, 44, 12, 44, 352, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, - 44, 5, 44, 360, 8, 44, 10, 44, 12, 44, 363, 9, 44, 1, 44, 1, 44, 1, 44, - 1, 44, 1, 44, 5, 44, 370, 8, 44, 10, 44, 12, 44, 373, 9, 44, 1, 44, 1, - 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 383, 8, 44, 10, 44, - 12, 44, 386, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, - 44, 1, 44, 1, 44, 5, 44, 398, 8, 44, 10, 44, 12, 44, 401, 9, 44, 1, 44, - 1, 44, 1, 44, 1, 44, 3, 44, 407, 8, 44, 1, 45, 1, 45, 1, 45, 1, 46, 1, - 46, 3, 46, 414, 8, 46, 1, 46, 1, 46, 1, 46, 5, 46, 419, 8, 46, 10, 46, - 12, 46, 422, 9, 46, 4, 336, 350, 384, 399, 0, 47, 1, 1, 3, 2, 5, 3, 7, - 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 21, 11, 23, 12, 25, 13, 27, - 14, 29, 15, 31, 16, 33, 17, 35, 18, 37, 19, 39, 20, 41, 21, 43, 22, 45, - 23, 47, 24, 49, 25, 51, 26, 53, 27, 55, 28, 57, 0, 59, 0, 61, 0, 63, 0, - 65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, 0, 79, 29, 81, 30, 83, 31, - 85, 32, 87, 33, 89, 34, 91, 35, 93, 36, 1, 0, 16, 2, 0, 65, 90, 97, 122, - 2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, - 102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, - 98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120, - 120, 3, 0, 9, 10, 12, 13, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, - 4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, - 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, - 39, 2, 0, 66, 66, 98, 98, 456, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, - 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, - 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, - 21, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0, - 0, 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, - 0, 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 0, 43, 1, 0, - 0, 0, 0, 45, 1, 0, 0, 0, 0, 47, 1, 0, 0, 0, 0, 49, 1, 0, 0, 0, 0, 51, 1, - 0, 0, 0, 0, 53, 1, 0, 0, 0, 0, 55, 1, 0, 0, 0, 0, 79, 1, 0, 0, 0, 0, 81, - 1, 0, 0, 0, 0, 83, 1, 0, 0, 0, 0, 85, 1, 0, 0, 0, 0, 87, 1, 0, 0, 0, 0, - 89, 1, 0, 0, 0, 0, 91, 1, 0, 0, 0, 0, 93, 1, 0, 0, 0, 1, 95, 1, 0, 0, 0, - 3, 98, 1, 0, 0, 0, 5, 101, 1, 0, 0, 0, 7, 104, 1, 0, 0, 0, 9, 106, 1, 0, - 0, 0, 11, 109, 1, 0, 0, 0, 13, 112, 1, 0, 0, 0, 15, 114, 1, 0, 0, 0, 17, - 117, 1, 0, 0, 0, 19, 120, 1, 0, 0, 0, 21, 122, 1, 0, 0, 0, 23, 124, 1, - 0, 0, 0, 25, 126, 1, 0, 0, 0, 27, 128, 1, 0, 0, 0, 29, 130, 1, 0, 0, 0, - 31, 132, 1, 0, 0, 0, 33, 134, 1, 0, 0, 0, 35, 136, 1, 0, 0, 0, 37, 138, - 1, 0, 0, 0, 39, 140, 1, 0, 0, 0, 41, 142, 1, 0, 0, 0, 43, 144, 1, 0, 0, - 0, 45, 146, 1, 0, 0, 0, 47, 148, 1, 0, 0, 0, 49, 150, 1, 0, 0, 0, 51, 152, - 1, 0, 0, 0, 53, 157, 1, 0, 0, 0, 55, 163, 1, 0, 0, 0, 57, 168, 1, 0, 0, - 0, 59, 170, 1, 0, 0, 0, 61, 172, 1, 0, 0, 0, 63, 174, 1, 0, 0, 0, 65, 183, - 1, 0, 0, 0, 67, 185, 1, 0, 0, 0, 69, 191, 1, 0, 0, 0, 71, 193, 1, 0, 0, - 0, 73, 196, 1, 0, 0, 0, 75, 201, 1, 0, 0, 0, 77, 224, 1, 0, 0, 0, 79, 227, - 1, 0, 0, 0, 81, 233, 1, 0, 0, 0, 83, 274, 1, 0, 0, 0, 85, 289, 1, 0, 0, - 0, 87, 308, 1, 0, 0, 0, 89, 406, 1, 0, 0, 0, 91, 408, 1, 0, 0, 0, 93, 413, - 1, 0, 0, 0, 95, 96, 5, 61, 0, 0, 96, 97, 5, 61, 0, 0, 97, 2, 1, 0, 0, 0, - 98, 99, 5, 33, 0, 0, 99, 100, 5, 61, 0, 0, 100, 4, 1, 0, 0, 0, 101, 102, - 5, 105, 0, 0, 102, 103, 5, 110, 0, 0, 103, 6, 1, 0, 0, 0, 104, 105, 5, - 60, 0, 0, 105, 8, 1, 0, 0, 0, 106, 107, 5, 60, 0, 0, 107, 108, 5, 61, 0, - 0, 108, 10, 1, 0, 0, 0, 109, 110, 5, 62, 0, 0, 110, 111, 5, 61, 0, 0, 111, - 12, 1, 0, 0, 0, 112, 113, 5, 62, 0, 0, 113, 14, 1, 0, 0, 0, 114, 115, 5, - 38, 0, 0, 115, 116, 5, 38, 0, 0, 116, 16, 1, 0, 0, 0, 117, 118, 5, 124, - 0, 0, 118, 119, 5, 124, 0, 0, 119, 18, 1, 0, 0, 0, 120, 121, 5, 91, 0, - 0, 121, 20, 1, 0, 0, 0, 122, 123, 5, 93, 0, 0, 123, 22, 1, 0, 0, 0, 124, - 125, 5, 123, 0, 0, 125, 24, 1, 0, 0, 0, 126, 127, 5, 125, 0, 0, 127, 26, - 1, 0, 0, 0, 128, 129, 5, 40, 0, 0, 129, 28, 1, 0, 0, 0, 130, 131, 5, 41, - 0, 0, 131, 30, 1, 0, 0, 0, 132, 133, 5, 46, 0, 0, 133, 32, 1, 0, 0, 0, - 134, 135, 5, 44, 0, 0, 135, 34, 1, 0, 0, 0, 136, 137, 5, 45, 0, 0, 137, - 36, 1, 0, 0, 0, 138, 139, 5, 33, 0, 0, 139, 38, 1, 0, 0, 0, 140, 141, 5, - 63, 0, 0, 141, 40, 1, 0, 0, 0, 142, 143, 5, 58, 0, 0, 143, 42, 1, 0, 0, - 0, 144, 145, 5, 43, 0, 0, 145, 44, 1, 0, 0, 0, 146, 147, 5, 42, 0, 0, 147, - 46, 1, 0, 0, 0, 148, 149, 5, 47, 0, 0, 149, 48, 1, 0, 0, 0, 150, 151, 5, - 37, 0, 0, 151, 50, 1, 0, 0, 0, 152, 153, 5, 116, 0, 0, 153, 154, 5, 114, - 0, 0, 154, 155, 5, 117, 0, 0, 155, 156, 5, 101, 0, 0, 156, 52, 1, 0, 0, - 0, 157, 158, 5, 102, 0, 0, 158, 159, 5, 97, 0, 0, 159, 160, 5, 108, 0, - 0, 160, 161, 5, 115, 0, 0, 161, 162, 5, 101, 0, 0, 162, 54, 1, 0, 0, 0, - 163, 164, 5, 110, 0, 0, 164, 165, 5, 117, 0, 0, 165, 166, 5, 108, 0, 0, - 166, 167, 5, 108, 0, 0, 167, 56, 1, 0, 0, 0, 168, 169, 5, 92, 0, 0, 169, - 58, 1, 0, 0, 0, 170, 171, 7, 0, 0, 0, 171, 60, 1, 0, 0, 0, 172, 173, 2, - 48, 57, 0, 173, 62, 1, 0, 0, 0, 174, 176, 7, 1, 0, 0, 175, 177, 7, 2, 0, - 0, 176, 175, 1, 0, 0, 0, 176, 177, 1, 0, 0, 0, 177, 179, 1, 0, 0, 0, 178, - 180, 3, 61, 30, 0, 179, 178, 1, 0, 0, 0, 180, 181, 1, 0, 0, 0, 181, 179, - 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 64, 1, 0, 0, 0, 183, 184, 7, 3, - 0, 0, 184, 66, 1, 0, 0, 0, 185, 186, 7, 4, 0, 0, 186, 68, 1, 0, 0, 0, 187, - 192, 3, 71, 35, 0, 188, 192, 3, 75, 37, 0, 189, 192, 3, 77, 38, 0, 190, - 192, 3, 73, 36, 0, 191, 187, 1, 0, 0, 0, 191, 188, 1, 0, 0, 0, 191, 189, - 1, 0, 0, 0, 191, 190, 1, 0, 0, 0, 192, 70, 1, 0, 0, 0, 193, 194, 3, 57, - 28, 0, 194, 195, 7, 5, 0, 0, 195, 72, 1, 0, 0, 0, 196, 197, 3, 57, 28, - 0, 197, 198, 2, 48, 51, 0, 198, 199, 2, 48, 55, 0, 199, 200, 2, 48, 55, - 0, 200, 74, 1, 0, 0, 0, 201, 202, 3, 57, 28, 0, 202, 203, 7, 6, 0, 0, 203, - 204, 3, 65, 32, 0, 204, 205, 3, 65, 32, 0, 205, 76, 1, 0, 0, 0, 206, 207, - 3, 57, 28, 0, 207, 208, 5, 117, 0, 0, 208, 209, 3, 65, 32, 0, 209, 210, - 3, 65, 32, 0, 210, 211, 3, 65, 32, 0, 211, 212, 3, 65, 32, 0, 212, 225, - 1, 0, 0, 0, 213, 214, 3, 57, 28, 0, 214, 215, 5, 85, 0, 0, 215, 216, 3, - 65, 32, 0, 216, 217, 3, 65, 32, 0, 217, 218, 3, 65, 32, 0, 218, 219, 3, - 65, 32, 0, 219, 220, 3, 65, 32, 0, 220, 221, 3, 65, 32, 0, 221, 222, 3, - 65, 32, 0, 222, 223, 3, 65, 32, 0, 223, 225, 1, 0, 0, 0, 224, 206, 1, 0, - 0, 0, 224, 213, 1, 0, 0, 0, 225, 78, 1, 0, 0, 0, 226, 228, 7, 7, 0, 0, - 227, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 227, 1, 0, 0, 0, 229, - 230, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 232, 6, 39, 0, 0, 232, 80, - 1, 0, 0, 0, 233, 234, 5, 47, 0, 0, 234, 235, 5, 47, 0, 0, 235, 239, 1, - 0, 0, 0, 236, 238, 8, 8, 0, 0, 237, 236, 1, 0, 0, 0, 238, 241, 1, 0, 0, - 0, 239, 237, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 242, 1, 0, 0, 0, 241, - 239, 1, 0, 0, 0, 242, 243, 6, 40, 0, 0, 243, 82, 1, 0, 0, 0, 244, 246, - 3, 61, 30, 0, 245, 244, 1, 0, 0, 0, 246, 247, 1, 0, 0, 0, 247, 245, 1, - 0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 249, 1, 0, 0, 0, 249, 251, 5, 46, 0, - 0, 250, 252, 3, 61, 30, 0, 251, 250, 1, 0, 0, 0, 252, 253, 1, 0, 0, 0, - 253, 251, 1, 0, 0, 0, 253, 254, 1, 0, 0, 0, 254, 256, 1, 0, 0, 0, 255, - 257, 3, 63, 31, 0, 256, 255, 1, 0, 0, 0, 256, 257, 1, 0, 0, 0, 257, 275, - 1, 0, 0, 0, 258, 260, 3, 61, 30, 0, 259, 258, 1, 0, 0, 0, 260, 261, 1, - 0, 0, 0, 261, 259, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 263, 1, 0, 0, - 0, 263, 264, 3, 63, 31, 0, 264, 275, 1, 0, 0, 0, 265, 267, 5, 46, 0, 0, - 266, 268, 3, 61, 30, 0, 267, 266, 1, 0, 0, 0, 268, 269, 1, 0, 0, 0, 269, - 267, 1, 0, 0, 0, 269, 270, 1, 0, 0, 0, 270, 272, 1, 0, 0, 0, 271, 273, - 3, 63, 31, 0, 272, 271, 1, 0, 0, 0, 272, 273, 1, 0, 0, 0, 273, 275, 1, - 0, 0, 0, 274, 245, 1, 0, 0, 0, 274, 259, 1, 0, 0, 0, 274, 265, 1, 0, 0, - 0, 275, 84, 1, 0, 0, 0, 276, 278, 3, 61, 30, 0, 277, 276, 1, 0, 0, 0, 278, - 279, 1, 0, 0, 0, 279, 277, 1, 0, 0, 0, 279, 280, 1, 0, 0, 0, 280, 290, - 1, 0, 0, 0, 281, 282, 5, 48, 0, 0, 282, 283, 5, 120, 0, 0, 283, 285, 1, - 0, 0, 0, 284, 286, 3, 65, 32, 0, 285, 284, 1, 0, 0, 0, 286, 287, 1, 0, - 0, 0, 287, 285, 1, 0, 0, 0, 287, 288, 1, 0, 0, 0, 288, 290, 1, 0, 0, 0, - 289, 277, 1, 0, 0, 0, 289, 281, 1, 0, 0, 0, 290, 86, 1, 0, 0, 0, 291, 293, - 3, 61, 30, 0, 292, 291, 1, 0, 0, 0, 293, 294, 1, 0, 0, 0, 294, 292, 1, - 0, 0, 0, 294, 295, 1, 0, 0, 0, 295, 296, 1, 0, 0, 0, 296, 297, 7, 9, 0, - 0, 297, 309, 1, 0, 0, 0, 298, 299, 5, 48, 0, 0, 299, 300, 5, 120, 0, 0, - 300, 302, 1, 0, 0, 0, 301, 303, 3, 65, 32, 0, 302, 301, 1, 0, 0, 0, 303, - 304, 1, 0, 0, 0, 304, 302, 1, 0, 0, 0, 304, 305, 1, 0, 0, 0, 305, 306, - 1, 0, 0, 0, 306, 307, 7, 9, 0, 0, 307, 309, 1, 0, 0, 0, 308, 292, 1, 0, - 0, 0, 308, 298, 1, 0, 0, 0, 309, 88, 1, 0, 0, 0, 310, 315, 5, 34, 0, 0, - 311, 314, 3, 69, 34, 0, 312, 314, 8, 10, 0, 0, 313, 311, 1, 0, 0, 0, 313, - 312, 1, 0, 0, 0, 314, 317, 1, 0, 0, 0, 315, 313, 1, 0, 0, 0, 315, 316, - 1, 0, 0, 0, 316, 318, 1, 0, 0, 0, 317, 315, 1, 0, 0, 0, 318, 407, 5, 34, - 0, 0, 319, 324, 5, 39, 0, 0, 320, 323, 3, 69, 34, 0, 321, 323, 8, 11, 0, - 0, 322, 320, 1, 0, 0, 0, 322, 321, 1, 0, 0, 0, 323, 326, 1, 0, 0, 0, 324, - 322, 1, 0, 0, 0, 324, 325, 1, 0, 0, 0, 325, 327, 1, 0, 0, 0, 326, 324, - 1, 0, 0, 0, 327, 407, 5, 39, 0, 0, 328, 329, 5, 34, 0, 0, 329, 330, 5, - 34, 0, 0, 330, 331, 5, 34, 0, 0, 331, 336, 1, 0, 0, 0, 332, 335, 3, 69, - 34, 0, 333, 335, 8, 12, 0, 0, 334, 332, 1, 0, 0, 0, 334, 333, 1, 0, 0, - 0, 335, 338, 1, 0, 0, 0, 336, 337, 1, 0, 0, 0, 336, 334, 1, 0, 0, 0, 337, - 339, 1, 0, 0, 0, 338, 336, 1, 0, 0, 0, 339, 340, 5, 34, 0, 0, 340, 341, - 5, 34, 0, 0, 341, 407, 5, 34, 0, 0, 342, 343, 5, 39, 0, 0, 343, 344, 5, - 39, 0, 0, 344, 345, 5, 39, 0, 0, 345, 350, 1, 0, 0, 0, 346, 349, 3, 69, - 34, 0, 347, 349, 8, 12, 0, 0, 348, 346, 1, 0, 0, 0, 348, 347, 1, 0, 0, - 0, 349, 352, 1, 0, 0, 0, 350, 351, 1, 0, 0, 0, 350, 348, 1, 0, 0, 0, 351, - 353, 1, 0, 0, 0, 352, 350, 1, 0, 0, 0, 353, 354, 5, 39, 0, 0, 354, 355, - 5, 39, 0, 0, 355, 407, 5, 39, 0, 0, 356, 357, 3, 67, 33, 0, 357, 361, 5, - 34, 0, 0, 358, 360, 8, 13, 0, 0, 359, 358, 1, 0, 0, 0, 360, 363, 1, 0, - 0, 0, 361, 359, 1, 0, 0, 0, 361, 362, 1, 0, 0, 0, 362, 364, 1, 0, 0, 0, - 363, 361, 1, 0, 0, 0, 364, 365, 5, 34, 0, 0, 365, 407, 1, 0, 0, 0, 366, - 367, 3, 67, 33, 0, 367, 371, 5, 39, 0, 0, 368, 370, 8, 14, 0, 0, 369, 368, - 1, 0, 0, 0, 370, 373, 1, 0, 0, 0, 371, 369, 1, 0, 0, 0, 371, 372, 1, 0, - 0, 0, 372, 374, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 374, 375, 5, 39, 0, 0, - 375, 407, 1, 0, 0, 0, 376, 377, 3, 67, 33, 0, 377, 378, 5, 34, 0, 0, 378, - 379, 5, 34, 0, 0, 379, 380, 5, 34, 0, 0, 380, 384, 1, 0, 0, 0, 381, 383, - 9, 0, 0, 0, 382, 381, 1, 0, 0, 0, 383, 386, 1, 0, 0, 0, 384, 385, 1, 0, - 0, 0, 384, 382, 1, 0, 0, 0, 385, 387, 1, 0, 0, 0, 386, 384, 1, 0, 0, 0, - 387, 388, 5, 34, 0, 0, 388, 389, 5, 34, 0, 0, 389, 390, 5, 34, 0, 0, 390, - 407, 1, 0, 0, 0, 391, 392, 3, 67, 33, 0, 392, 393, 5, 39, 0, 0, 393, 394, - 5, 39, 0, 0, 394, 395, 5, 39, 0, 0, 395, 399, 1, 0, 0, 0, 396, 398, 9, - 0, 0, 0, 397, 396, 1, 0, 0, 0, 398, 401, 1, 0, 0, 0, 399, 400, 1, 0, 0, - 0, 399, 397, 1, 0, 0, 0, 400, 402, 1, 0, 0, 0, 401, 399, 1, 0, 0, 0, 402, - 403, 5, 39, 0, 0, 403, 404, 5, 39, 0, 0, 404, 405, 5, 39, 0, 0, 405, 407, - 1, 0, 0, 0, 406, 310, 1, 0, 0, 0, 406, 319, 1, 0, 0, 0, 406, 328, 1, 0, - 0, 0, 406, 342, 1, 0, 0, 0, 406, 356, 1, 0, 0, 0, 406, 366, 1, 0, 0, 0, - 406, 376, 1, 0, 0, 0, 406, 391, 1, 0, 0, 0, 407, 90, 1, 0, 0, 0, 408, 409, - 7, 15, 0, 0, 409, 410, 3, 89, 44, 0, 410, 92, 1, 0, 0, 0, 411, 414, 3, - 59, 29, 0, 412, 414, 5, 95, 0, 0, 413, 411, 1, 0, 0, 0, 413, 412, 1, 0, - 0, 0, 414, 420, 1, 0, 0, 0, 415, 419, 3, 59, 29, 0, 416, 419, 3, 61, 30, - 0, 417, 419, 5, 95, 0, 0, 418, 415, 1, 0, 0, 0, 418, 416, 1, 0, 0, 0, 418, - 417, 1, 0, 0, 0, 419, 422, 1, 0, 0, 0, 420, 418, 1, 0, 0, 0, 420, 421, - 1, 0, 0, 0, 421, 94, 1, 0, 0, 0, 422, 420, 1, 0, 0, 0, 36, 0, 176, 181, - 191, 224, 229, 239, 247, 253, 256, 261, 269, 272, 274, 279, 287, 289, 294, - 304, 308, 313, 315, 322, 324, 334, 336, 348, 350, 361, 371, 384, 399, 406, - 413, 418, 420, 1, 0, 1, 0, -} - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } + staticData := &CELLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "'=='", "'!='", "'in'", "'<'", "'<='", "'>='", "'>'", "'&&'", "'||'", + "'['", "']'", "'{'", "'}'", "'('", "')'", "'.'", "','", "'-'", "'!'", + "'?'", "':'", "'+'", "'*'", "'/'", "'%'", "'true'", "'false'", "'null'", + } + staticData.SymbolicNames = []string{ + "", "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", + "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", + "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", + "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", + "NUL", "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", + "STRING", "BYTES", "IDENTIFIER", "ESC_IDENTIFIER", + } + staticData.RuleNames = []string{ + "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", + "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", + "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", + "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", + "NUL", "BACKSLASH", "LETTER", "DIGIT", "EXPONENT", "HEXDIGIT", "RAW", + "ESC_SEQ", "ESC_CHAR_SEQ", "ESC_OCT_SEQ", "ESC_BYTE_SEQ", "ESC_UNI_SEQ", + "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", "STRING", + "BYTES", "IDENTIFIER", "ESC_IDENTIFIER", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 37, 435, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, + 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, + 7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7, + 20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25, + 2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2, + 31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36, + 7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7, + 41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46, + 2, 47, 7, 47, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, + 3, 1, 3, 1, 4, 1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, + 7, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, + 12, 1, 13, 1, 13, 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 17, 1, 17, + 1, 18, 1, 18, 1, 19, 1, 19, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, + 23, 1, 23, 1, 24, 1, 24, 1, 25, 1, 25, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, + 1, 26, 1, 26, 1, 26, 1, 26, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 28, 1, + 28, 1, 29, 1, 29, 1, 30, 1, 30, 1, 31, 1, 31, 3, 31, 179, 8, 31, 1, 31, + 4, 31, 182, 8, 31, 11, 31, 12, 31, 183, 1, 32, 1, 32, 1, 33, 1, 33, 1, + 34, 1, 34, 1, 34, 1, 34, 3, 34, 194, 8, 34, 1, 35, 1, 35, 1, 35, 1, 36, + 1, 36, 1, 36, 1, 36, 1, 36, 1, 37, 1, 37, 1, 37, 1, 37, 1, 37, 1, 38, 1, + 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, + 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 3, 38, 227, 8, 38, 1, 39, 4, + 39, 230, 8, 39, 11, 39, 12, 39, 231, 1, 39, 1, 39, 1, 40, 1, 40, 1, 40, + 1, 40, 5, 40, 240, 8, 40, 10, 40, 12, 40, 243, 9, 40, 1, 40, 1, 40, 1, + 41, 4, 41, 248, 8, 41, 11, 41, 12, 41, 249, 1, 41, 1, 41, 4, 41, 254, 8, + 41, 11, 41, 12, 41, 255, 1, 41, 3, 41, 259, 8, 41, 1, 41, 4, 41, 262, 8, + 41, 11, 41, 12, 41, 263, 1, 41, 1, 41, 1, 41, 1, 41, 4, 41, 270, 8, 41, + 11, 41, 12, 41, 271, 1, 41, 3, 41, 275, 8, 41, 3, 41, 277, 8, 41, 1, 42, + 4, 42, 280, 8, 42, 11, 42, 12, 42, 281, 1, 42, 1, 42, 1, 42, 1, 42, 4, + 42, 288, 8, 42, 11, 42, 12, 42, 289, 3, 42, 292, 8, 42, 1, 43, 4, 43, 295, + 8, 43, 11, 43, 12, 43, 296, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 4, + 43, 305, 8, 43, 11, 43, 12, 43, 306, 1, 43, 1, 43, 3, 43, 311, 8, 43, 1, + 44, 1, 44, 1, 44, 5, 44, 316, 8, 44, 10, 44, 12, 44, 319, 9, 44, 1, 44, + 1, 44, 1, 44, 1, 44, 5, 44, 325, 8, 44, 10, 44, 12, 44, 328, 9, 44, 1, + 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 337, 8, 44, 10, 44, + 12, 44, 340, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, + 44, 1, 44, 5, 44, 351, 8, 44, 10, 44, 12, 44, 354, 9, 44, 1, 44, 1, 44, + 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 362, 8, 44, 10, 44, 12, 44, 365, 9, + 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 372, 8, 44, 10, 44, 12, 44, + 375, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, + 44, 385, 8, 44, 10, 44, 12, 44, 388, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, + 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 400, 8, 44, 10, 44, 12, + 44, 403, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 3, 44, 409, 8, 44, 1, 45, 1, + 45, 1, 45, 1, 46, 1, 46, 3, 46, 416, 8, 46, 1, 46, 1, 46, 1, 46, 5, 46, + 421, 8, 46, 10, 46, 12, 46, 424, 9, 46, 1, 47, 1, 47, 1, 47, 1, 47, 4, + 47, 430, 8, 47, 11, 47, 12, 47, 431, 1, 47, 1, 47, 4, 338, 352, 386, 401, + 0, 48, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, + 21, 11, 23, 12, 25, 13, 27, 14, 29, 15, 31, 16, 33, 17, 35, 18, 37, 19, + 39, 20, 41, 21, 43, 22, 45, 23, 47, 24, 49, 25, 51, 26, 53, 27, 55, 28, + 57, 0, 59, 0, 61, 0, 63, 0, 65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, + 0, 79, 29, 81, 30, 83, 31, 85, 32, 87, 33, 89, 34, 91, 35, 93, 36, 95, + 37, 1, 0, 17, 2, 0, 65, 90, 97, 122, 2, 0, 69, 69, 101, 101, 2, 0, 43, + 43, 45, 45, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 82, 82, 114, 114, 10, + 0, 34, 34, 39, 39, 63, 63, 92, 92, 96, 98, 102, 102, 110, 110, 114, 114, + 116, 116, 118, 118, 2, 0, 88, 88, 120, 120, 3, 0, 9, 10, 12, 13, 32, 32, + 1, 0, 10, 10, 2, 0, 85, 85, 117, 117, 4, 0, 10, 10, 13, 13, 34, 34, 92, + 92, 4, 0, 10, 10, 13, 13, 39, 39, 92, 92, 1, 0, 92, 92, 3, 0, 10, 10, 13, + 13, 34, 34, 3, 0, 10, 10, 13, 13, 39, 39, 2, 0, 66, 66, 98, 98, 3, 0, 32, + 32, 45, 47, 95, 95, 471, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, + 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, + 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 21, + 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0, 0, + 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0, 0, + 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 0, 43, 1, 0, 0, + 0, 0, 45, 1, 0, 0, 0, 0, 47, 1, 0, 0, 0, 0, 49, 1, 0, 0, 0, 0, 51, 1, 0, + 0, 0, 0, 53, 1, 0, 0, 0, 0, 55, 1, 0, 0, 0, 0, 79, 1, 0, 0, 0, 0, 81, 1, + 0, 0, 0, 0, 83, 1, 0, 0, 0, 0, 85, 1, 0, 0, 0, 0, 87, 1, 0, 0, 0, 0, 89, + 1, 0, 0, 0, 0, 91, 1, 0, 0, 0, 0, 93, 1, 0, 0, 0, 0, 95, 1, 0, 0, 0, 1, + 97, 1, 0, 0, 0, 3, 100, 1, 0, 0, 0, 5, 103, 1, 0, 0, 0, 7, 106, 1, 0, 0, + 0, 9, 108, 1, 0, 0, 0, 11, 111, 1, 0, 0, 0, 13, 114, 1, 0, 0, 0, 15, 116, + 1, 0, 0, 0, 17, 119, 1, 0, 0, 0, 19, 122, 1, 0, 0, 0, 21, 124, 1, 0, 0, + 0, 23, 126, 1, 0, 0, 0, 25, 128, 1, 0, 0, 0, 27, 130, 1, 0, 0, 0, 29, 132, + 1, 0, 0, 0, 31, 134, 1, 0, 0, 0, 33, 136, 1, 0, 0, 0, 35, 138, 1, 0, 0, + 0, 37, 140, 1, 0, 0, 0, 39, 142, 1, 0, 0, 0, 41, 144, 1, 0, 0, 0, 43, 146, + 1, 0, 0, 0, 45, 148, 1, 0, 0, 0, 47, 150, 1, 0, 0, 0, 49, 152, 1, 0, 0, + 0, 51, 154, 1, 0, 0, 0, 53, 159, 1, 0, 0, 0, 55, 165, 1, 0, 0, 0, 57, 170, + 1, 0, 0, 0, 59, 172, 1, 0, 0, 0, 61, 174, 1, 0, 0, 0, 63, 176, 1, 0, 0, + 0, 65, 185, 1, 0, 0, 0, 67, 187, 1, 0, 0, 0, 69, 193, 1, 0, 0, 0, 71, 195, + 1, 0, 0, 0, 73, 198, 1, 0, 0, 0, 75, 203, 1, 0, 0, 0, 77, 226, 1, 0, 0, + 0, 79, 229, 1, 0, 0, 0, 81, 235, 1, 0, 0, 0, 83, 276, 1, 0, 0, 0, 85, 291, + 1, 0, 0, 0, 87, 310, 1, 0, 0, 0, 89, 408, 1, 0, 0, 0, 91, 410, 1, 0, 0, + 0, 93, 415, 1, 0, 0, 0, 95, 425, 1, 0, 0, 0, 97, 98, 5, 61, 0, 0, 98, 99, + 5, 61, 0, 0, 99, 2, 1, 0, 0, 0, 100, 101, 5, 33, 0, 0, 101, 102, 5, 61, + 0, 0, 102, 4, 1, 0, 0, 0, 103, 104, 5, 105, 0, 0, 104, 105, 5, 110, 0, + 0, 105, 6, 1, 0, 0, 0, 106, 107, 5, 60, 0, 0, 107, 8, 1, 0, 0, 0, 108, + 109, 5, 60, 0, 0, 109, 110, 5, 61, 0, 0, 110, 10, 1, 0, 0, 0, 111, 112, + 5, 62, 0, 0, 112, 113, 5, 61, 0, 0, 113, 12, 1, 0, 0, 0, 114, 115, 5, 62, + 0, 0, 115, 14, 1, 0, 0, 0, 116, 117, 5, 38, 0, 0, 117, 118, 5, 38, 0, 0, + 118, 16, 1, 0, 0, 0, 119, 120, 5, 124, 0, 0, 120, 121, 5, 124, 0, 0, 121, + 18, 1, 0, 0, 0, 122, 123, 5, 91, 0, 0, 123, 20, 1, 0, 0, 0, 124, 125, 5, + 93, 0, 0, 125, 22, 1, 0, 0, 0, 126, 127, 5, 123, 0, 0, 127, 24, 1, 0, 0, + 0, 128, 129, 5, 125, 0, 0, 129, 26, 1, 0, 0, 0, 130, 131, 5, 40, 0, 0, + 131, 28, 1, 0, 0, 0, 132, 133, 5, 41, 0, 0, 133, 30, 1, 0, 0, 0, 134, 135, + 5, 46, 0, 0, 135, 32, 1, 0, 0, 0, 136, 137, 5, 44, 0, 0, 137, 34, 1, 0, + 0, 0, 138, 139, 5, 45, 0, 0, 139, 36, 1, 0, 0, 0, 140, 141, 5, 33, 0, 0, + 141, 38, 1, 0, 0, 0, 142, 143, 5, 63, 0, 0, 143, 40, 1, 0, 0, 0, 144, 145, + 5, 58, 0, 0, 145, 42, 1, 0, 0, 0, 146, 147, 5, 43, 0, 0, 147, 44, 1, 0, + 0, 0, 148, 149, 5, 42, 0, 0, 149, 46, 1, 0, 0, 0, 150, 151, 5, 47, 0, 0, + 151, 48, 1, 0, 0, 0, 152, 153, 5, 37, 0, 0, 153, 50, 1, 0, 0, 0, 154, 155, + 5, 116, 0, 0, 155, 156, 5, 114, 0, 0, 156, 157, 5, 117, 0, 0, 157, 158, + 5, 101, 0, 0, 158, 52, 1, 0, 0, 0, 159, 160, 5, 102, 0, 0, 160, 161, 5, + 97, 0, 0, 161, 162, 5, 108, 0, 0, 162, 163, 5, 115, 0, 0, 163, 164, 5, + 101, 0, 0, 164, 54, 1, 0, 0, 0, 165, 166, 5, 110, 0, 0, 166, 167, 5, 117, + 0, 0, 167, 168, 5, 108, 0, 0, 168, 169, 5, 108, 0, 0, 169, 56, 1, 0, 0, + 0, 170, 171, 5, 92, 0, 0, 171, 58, 1, 0, 0, 0, 172, 173, 7, 0, 0, 0, 173, + 60, 1, 0, 0, 0, 174, 175, 2, 48, 57, 0, 175, 62, 1, 0, 0, 0, 176, 178, + 7, 1, 0, 0, 177, 179, 7, 2, 0, 0, 178, 177, 1, 0, 0, 0, 178, 179, 1, 0, + 0, 0, 179, 181, 1, 0, 0, 0, 180, 182, 3, 61, 30, 0, 181, 180, 1, 0, 0, + 0, 182, 183, 1, 0, 0, 0, 183, 181, 1, 0, 0, 0, 183, 184, 1, 0, 0, 0, 184, + 64, 1, 0, 0, 0, 185, 186, 7, 3, 0, 0, 186, 66, 1, 0, 0, 0, 187, 188, 7, + 4, 0, 0, 188, 68, 1, 0, 0, 0, 189, 194, 3, 71, 35, 0, 190, 194, 3, 75, + 37, 0, 191, 194, 3, 77, 38, 0, 192, 194, 3, 73, 36, 0, 193, 189, 1, 0, + 0, 0, 193, 190, 1, 0, 0, 0, 193, 191, 1, 0, 0, 0, 193, 192, 1, 0, 0, 0, + 194, 70, 1, 0, 0, 0, 195, 196, 3, 57, 28, 0, 196, 197, 7, 5, 0, 0, 197, + 72, 1, 0, 0, 0, 198, 199, 3, 57, 28, 0, 199, 200, 2, 48, 51, 0, 200, 201, + 2, 48, 55, 0, 201, 202, 2, 48, 55, 0, 202, 74, 1, 0, 0, 0, 203, 204, 3, + 57, 28, 0, 204, 205, 7, 6, 0, 0, 205, 206, 3, 65, 32, 0, 206, 207, 3, 65, + 32, 0, 207, 76, 1, 0, 0, 0, 208, 209, 3, 57, 28, 0, 209, 210, 5, 117, 0, + 0, 210, 211, 3, 65, 32, 0, 211, 212, 3, 65, 32, 0, 212, 213, 3, 65, 32, + 0, 213, 214, 3, 65, 32, 0, 214, 227, 1, 0, 0, 0, 215, 216, 3, 57, 28, 0, + 216, 217, 5, 85, 0, 0, 217, 218, 3, 65, 32, 0, 218, 219, 3, 65, 32, 0, + 219, 220, 3, 65, 32, 0, 220, 221, 3, 65, 32, 0, 221, 222, 3, 65, 32, 0, + 222, 223, 3, 65, 32, 0, 223, 224, 3, 65, 32, 0, 224, 225, 3, 65, 32, 0, + 225, 227, 1, 0, 0, 0, 226, 208, 1, 0, 0, 0, 226, 215, 1, 0, 0, 0, 227, + 78, 1, 0, 0, 0, 228, 230, 7, 7, 0, 0, 229, 228, 1, 0, 0, 0, 230, 231, 1, + 0, 0, 0, 231, 229, 1, 0, 0, 0, 231, 232, 1, 0, 0, 0, 232, 233, 1, 0, 0, + 0, 233, 234, 6, 39, 0, 0, 234, 80, 1, 0, 0, 0, 235, 236, 5, 47, 0, 0, 236, + 237, 5, 47, 0, 0, 237, 241, 1, 0, 0, 0, 238, 240, 8, 8, 0, 0, 239, 238, + 1, 0, 0, 0, 240, 243, 1, 0, 0, 0, 241, 239, 1, 0, 0, 0, 241, 242, 1, 0, + 0, 0, 242, 244, 1, 0, 0, 0, 243, 241, 1, 0, 0, 0, 244, 245, 6, 40, 0, 0, + 245, 82, 1, 0, 0, 0, 246, 248, 3, 61, 30, 0, 247, 246, 1, 0, 0, 0, 248, + 249, 1, 0, 0, 0, 249, 247, 1, 0, 0, 0, 249, 250, 1, 0, 0, 0, 250, 251, + 1, 0, 0, 0, 251, 253, 5, 46, 0, 0, 252, 254, 3, 61, 30, 0, 253, 252, 1, + 0, 0, 0, 254, 255, 1, 0, 0, 0, 255, 253, 1, 0, 0, 0, 255, 256, 1, 0, 0, + 0, 256, 258, 1, 0, 0, 0, 257, 259, 3, 63, 31, 0, 258, 257, 1, 0, 0, 0, + 258, 259, 1, 0, 0, 0, 259, 277, 1, 0, 0, 0, 260, 262, 3, 61, 30, 0, 261, + 260, 1, 0, 0, 0, 262, 263, 1, 0, 0, 0, 263, 261, 1, 0, 0, 0, 263, 264, + 1, 0, 0, 0, 264, 265, 1, 0, 0, 0, 265, 266, 3, 63, 31, 0, 266, 277, 1, + 0, 0, 0, 267, 269, 5, 46, 0, 0, 268, 270, 3, 61, 30, 0, 269, 268, 1, 0, + 0, 0, 270, 271, 1, 0, 0, 0, 271, 269, 1, 0, 0, 0, 271, 272, 1, 0, 0, 0, + 272, 274, 1, 0, 0, 0, 273, 275, 3, 63, 31, 0, 274, 273, 1, 0, 0, 0, 274, + 275, 1, 0, 0, 0, 275, 277, 1, 0, 0, 0, 276, 247, 1, 0, 0, 0, 276, 261, + 1, 0, 0, 0, 276, 267, 1, 0, 0, 0, 277, 84, 1, 0, 0, 0, 278, 280, 3, 61, + 30, 0, 279, 278, 1, 0, 0, 0, 280, 281, 1, 0, 0, 0, 281, 279, 1, 0, 0, 0, + 281, 282, 1, 0, 0, 0, 282, 292, 1, 0, 0, 0, 283, 284, 5, 48, 0, 0, 284, + 285, 5, 120, 0, 0, 285, 287, 1, 0, 0, 0, 286, 288, 3, 65, 32, 0, 287, 286, + 1, 0, 0, 0, 288, 289, 1, 0, 0, 0, 289, 287, 1, 0, 0, 0, 289, 290, 1, 0, + 0, 0, 290, 292, 1, 0, 0, 0, 291, 279, 1, 0, 0, 0, 291, 283, 1, 0, 0, 0, + 292, 86, 1, 0, 0, 0, 293, 295, 3, 61, 30, 0, 294, 293, 1, 0, 0, 0, 295, + 296, 1, 0, 0, 0, 296, 294, 1, 0, 0, 0, 296, 297, 1, 0, 0, 0, 297, 298, + 1, 0, 0, 0, 298, 299, 7, 9, 0, 0, 299, 311, 1, 0, 0, 0, 300, 301, 5, 48, + 0, 0, 301, 302, 5, 120, 0, 0, 302, 304, 1, 0, 0, 0, 303, 305, 3, 65, 32, + 0, 304, 303, 1, 0, 0, 0, 305, 306, 1, 0, 0, 0, 306, 304, 1, 0, 0, 0, 306, + 307, 1, 0, 0, 0, 307, 308, 1, 0, 0, 0, 308, 309, 7, 9, 0, 0, 309, 311, + 1, 0, 0, 0, 310, 294, 1, 0, 0, 0, 310, 300, 1, 0, 0, 0, 311, 88, 1, 0, + 0, 0, 312, 317, 5, 34, 0, 0, 313, 316, 3, 69, 34, 0, 314, 316, 8, 10, 0, + 0, 315, 313, 1, 0, 0, 0, 315, 314, 1, 0, 0, 0, 316, 319, 1, 0, 0, 0, 317, + 315, 1, 0, 0, 0, 317, 318, 1, 0, 0, 0, 318, 320, 1, 0, 0, 0, 319, 317, + 1, 0, 0, 0, 320, 409, 5, 34, 0, 0, 321, 326, 5, 39, 0, 0, 322, 325, 3, + 69, 34, 0, 323, 325, 8, 11, 0, 0, 324, 322, 1, 0, 0, 0, 324, 323, 1, 0, + 0, 0, 325, 328, 1, 0, 0, 0, 326, 324, 1, 0, 0, 0, 326, 327, 1, 0, 0, 0, + 327, 329, 1, 0, 0, 0, 328, 326, 1, 0, 0, 0, 329, 409, 5, 39, 0, 0, 330, + 331, 5, 34, 0, 0, 331, 332, 5, 34, 0, 0, 332, 333, 5, 34, 0, 0, 333, 338, + 1, 0, 0, 0, 334, 337, 3, 69, 34, 0, 335, 337, 8, 12, 0, 0, 336, 334, 1, + 0, 0, 0, 336, 335, 1, 0, 0, 0, 337, 340, 1, 0, 0, 0, 338, 339, 1, 0, 0, + 0, 338, 336, 1, 0, 0, 0, 339, 341, 1, 0, 0, 0, 340, 338, 1, 0, 0, 0, 341, + 342, 5, 34, 0, 0, 342, 343, 5, 34, 0, 0, 343, 409, 5, 34, 0, 0, 344, 345, + 5, 39, 0, 0, 345, 346, 5, 39, 0, 0, 346, 347, 5, 39, 0, 0, 347, 352, 1, + 0, 0, 0, 348, 351, 3, 69, 34, 0, 349, 351, 8, 12, 0, 0, 350, 348, 1, 0, + 0, 0, 350, 349, 1, 0, 0, 0, 351, 354, 1, 0, 0, 0, 352, 353, 1, 0, 0, 0, + 352, 350, 1, 0, 0, 0, 353, 355, 1, 0, 0, 0, 354, 352, 1, 0, 0, 0, 355, + 356, 5, 39, 0, 0, 356, 357, 5, 39, 0, 0, 357, 409, 5, 39, 0, 0, 358, 359, + 3, 67, 33, 0, 359, 363, 5, 34, 0, 0, 360, 362, 8, 13, 0, 0, 361, 360, 1, + 0, 0, 0, 362, 365, 1, 0, 0, 0, 363, 361, 1, 0, 0, 0, 363, 364, 1, 0, 0, + 0, 364, 366, 1, 0, 0, 0, 365, 363, 1, 0, 0, 0, 366, 367, 5, 34, 0, 0, 367, + 409, 1, 0, 0, 0, 368, 369, 3, 67, 33, 0, 369, 373, 5, 39, 0, 0, 370, 372, + 8, 14, 0, 0, 371, 370, 1, 0, 0, 0, 372, 375, 1, 0, 0, 0, 373, 371, 1, 0, + 0, 0, 373, 374, 1, 0, 0, 0, 374, 376, 1, 0, 0, 0, 375, 373, 1, 0, 0, 0, + 376, 377, 5, 39, 0, 0, 377, 409, 1, 0, 0, 0, 378, 379, 3, 67, 33, 0, 379, + 380, 5, 34, 0, 0, 380, 381, 5, 34, 0, 0, 381, 382, 5, 34, 0, 0, 382, 386, + 1, 0, 0, 0, 383, 385, 9, 0, 0, 0, 384, 383, 1, 0, 0, 0, 385, 388, 1, 0, + 0, 0, 386, 387, 1, 0, 0, 0, 386, 384, 1, 0, 0, 0, 387, 389, 1, 0, 0, 0, + 388, 386, 1, 0, 0, 0, 389, 390, 5, 34, 0, 0, 390, 391, 5, 34, 0, 0, 391, + 392, 5, 34, 0, 0, 392, 409, 1, 0, 0, 0, 393, 394, 3, 67, 33, 0, 394, 395, + 5, 39, 0, 0, 395, 396, 5, 39, 0, 0, 396, 397, 5, 39, 0, 0, 397, 401, 1, + 0, 0, 0, 398, 400, 9, 0, 0, 0, 399, 398, 1, 0, 0, 0, 400, 403, 1, 0, 0, + 0, 401, 402, 1, 0, 0, 0, 401, 399, 1, 0, 0, 0, 402, 404, 1, 0, 0, 0, 403, + 401, 1, 0, 0, 0, 404, 405, 5, 39, 0, 0, 405, 406, 5, 39, 0, 0, 406, 407, + 5, 39, 0, 0, 407, 409, 1, 0, 0, 0, 408, 312, 1, 0, 0, 0, 408, 321, 1, 0, + 0, 0, 408, 330, 1, 0, 0, 0, 408, 344, 1, 0, 0, 0, 408, 358, 1, 0, 0, 0, + 408, 368, 1, 0, 0, 0, 408, 378, 1, 0, 0, 0, 408, 393, 1, 0, 0, 0, 409, + 90, 1, 0, 0, 0, 410, 411, 7, 15, 0, 0, 411, 412, 3, 89, 44, 0, 412, 92, + 1, 0, 0, 0, 413, 416, 3, 59, 29, 0, 414, 416, 5, 95, 0, 0, 415, 413, 1, + 0, 0, 0, 415, 414, 1, 0, 0, 0, 416, 422, 1, 0, 0, 0, 417, 421, 3, 59, 29, + 0, 418, 421, 3, 61, 30, 0, 419, 421, 5, 95, 0, 0, 420, 417, 1, 0, 0, 0, + 420, 418, 1, 0, 0, 0, 420, 419, 1, 0, 0, 0, 421, 424, 1, 0, 0, 0, 422, + 420, 1, 0, 0, 0, 422, 423, 1, 0, 0, 0, 423, 94, 1, 0, 0, 0, 424, 422, 1, + 0, 0, 0, 425, 429, 5, 96, 0, 0, 426, 430, 3, 59, 29, 0, 427, 430, 3, 61, + 30, 0, 428, 430, 7, 16, 0, 0, 429, 426, 1, 0, 0, 0, 429, 427, 1, 0, 0, + 0, 429, 428, 1, 0, 0, 0, 430, 431, 1, 0, 0, 0, 431, 429, 1, 0, 0, 0, 431, + 432, 1, 0, 0, 0, 432, 433, 1, 0, 0, 0, 433, 434, 5, 96, 0, 0, 434, 96, + 1, 0, 0, 0, 38, 0, 178, 183, 193, 226, 231, 241, 249, 255, 258, 263, 271, + 274, 276, 281, 289, 291, 296, 306, 310, 315, 317, 324, 326, 336, 338, 350, + 352, 363, 373, 386, 401, 408, 415, 420, 422, 429, 431, 1, 0, 1, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } } // CELLexerInit initializes any static state used to implement CELLexer. By default the @@ -280,16 +287,16 @@ func cellexerLexerInit() { // NewCELLexer(). You can call this function if you wish to initialize the static state ahead // of time. func CELLexerInit() { - staticData := &CELLexerLexerStaticData - staticData.once.Do(cellexerLexerInit) + staticData := &CELLexerLexerStaticData + staticData.once.Do(cellexerLexerInit) } // NewCELLexer produces a new lexer instance for the optional input antlr.CharStream. func NewCELLexer(input antlr.CharStream) *CELLexer { - CELLexerInit() + CELLexerInit() l := new(CELLexer) l.BaseLexer = antlr.NewBaseLexer(input) - staticData := &CELLexerLexerStaticData + staticData := &CELLexerLexerStaticData l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) l.channelNames = staticData.ChannelNames l.modeNames = staticData.ModeNames @@ -304,41 +311,41 @@ func NewCELLexer(input antlr.CharStream) *CELLexer { // CELLexer tokens. const ( - CELLexerEQUALS = 1 - CELLexerNOT_EQUALS = 2 - CELLexerIN = 3 - CELLexerLESS = 4 - CELLexerLESS_EQUALS = 5 + CELLexerEQUALS = 1 + CELLexerNOT_EQUALS = 2 + CELLexerIN = 3 + CELLexerLESS = 4 + CELLexerLESS_EQUALS = 5 CELLexerGREATER_EQUALS = 6 - CELLexerGREATER = 7 - CELLexerLOGICAL_AND = 8 - CELLexerLOGICAL_OR = 9 - CELLexerLBRACKET = 10 - CELLexerRPRACKET = 11 - CELLexerLBRACE = 12 - CELLexerRBRACE = 13 - CELLexerLPAREN = 14 - CELLexerRPAREN = 15 - CELLexerDOT = 16 - CELLexerCOMMA = 17 - CELLexerMINUS = 18 - CELLexerEXCLAM = 19 - CELLexerQUESTIONMARK = 20 - CELLexerCOLON = 21 - CELLexerPLUS = 22 - CELLexerSTAR = 23 - CELLexerSLASH = 24 - CELLexerPERCENT = 25 - CELLexerCEL_TRUE = 26 - CELLexerCEL_FALSE = 27 - CELLexerNUL = 28 - CELLexerWHITESPACE = 29 - CELLexerCOMMENT = 30 - CELLexerNUM_FLOAT = 31 - CELLexerNUM_INT = 32 - CELLexerNUM_UINT = 33 - CELLexerSTRING = 34 - CELLexerBYTES = 35 - CELLexerIDENTIFIER = 36 + CELLexerGREATER = 7 + CELLexerLOGICAL_AND = 8 + CELLexerLOGICAL_OR = 9 + CELLexerLBRACKET = 10 + CELLexerRPRACKET = 11 + CELLexerLBRACE = 12 + CELLexerRBRACE = 13 + CELLexerLPAREN = 14 + CELLexerRPAREN = 15 + CELLexerDOT = 16 + CELLexerCOMMA = 17 + CELLexerMINUS = 18 + CELLexerEXCLAM = 19 + CELLexerQUESTIONMARK = 20 + CELLexerCOLON = 21 + CELLexerPLUS = 22 + CELLexerSTAR = 23 + CELLexerSLASH = 24 + CELLexerPERCENT = 25 + CELLexerCEL_TRUE = 26 + CELLexerCEL_FALSE = 27 + CELLexerNUL = 28 + CELLexerWHITESPACE = 29 + CELLexerCOMMENT = 30 + CELLexerNUM_FLOAT = 31 + CELLexerNUM_INT = 32 + CELLexerNUM_UINT = 33 + CELLexerSTRING = 34 + CELLexerBYTES = 35 + CELLexerIDENTIFIER = 36 + CELLexerESC_IDENTIFIER = 37 ) - diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_listener.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_listener.go index 22dc99789..da477c4b7 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_listener.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_listener.go @@ -1,9 +1,8 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen // CEL import "github.com/antlr4-go/antlr/v4" - // CELListener is a complete listener for a parse tree produced by CELParser. type CELListener interface { antlr.ParseTreeListener @@ -47,8 +46,11 @@ type CELListener interface { // EnterIndex is called when entering the Index production. EnterIndex(c *IndexContext) - // EnterIdentOrGlobalCall is called when entering the IdentOrGlobalCall production. - EnterIdentOrGlobalCall(c *IdentOrGlobalCallContext) + // EnterIdent is called when entering the Ident production. + EnterIdent(c *IdentContext) + + // EnterGlobalCall is called when entering the GlobalCall production. + EnterGlobalCall(c *GlobalCallContext) // EnterNested is called when entering the Nested production. EnterNested(c *NestedContext) @@ -80,6 +82,12 @@ type CELListener interface { // EnterMapInitializerList is called when entering the mapInitializerList production. EnterMapInitializerList(c *MapInitializerListContext) + // EnterSimpleIdentifier is called when entering the SimpleIdentifier production. + EnterSimpleIdentifier(c *SimpleIdentifierContext) + + // EnterEscapedIdentifier is called when entering the EscapedIdentifier production. + EnterEscapedIdentifier(c *EscapedIdentifierContext) + // EnterOptExpr is called when entering the optExpr production. EnterOptExpr(c *OptExprContext) @@ -146,8 +154,11 @@ type CELListener interface { // ExitIndex is called when exiting the Index production. ExitIndex(c *IndexContext) - // ExitIdentOrGlobalCall is called when exiting the IdentOrGlobalCall production. - ExitIdentOrGlobalCall(c *IdentOrGlobalCallContext) + // ExitIdent is called when exiting the Ident production. + ExitIdent(c *IdentContext) + + // ExitGlobalCall is called when exiting the GlobalCall production. + ExitGlobalCall(c *GlobalCallContext) // ExitNested is called when exiting the Nested production. ExitNested(c *NestedContext) @@ -179,6 +190,12 @@ type CELListener interface { // ExitMapInitializerList is called when exiting the mapInitializerList production. ExitMapInitializerList(c *MapInitializerListContext) + // ExitSimpleIdentifier is called when exiting the SimpleIdentifier production. + ExitSimpleIdentifier(c *SimpleIdentifierContext) + + // ExitEscapedIdentifier is called when exiting the EscapedIdentifier production. + ExitEscapedIdentifier(c *EscapedIdentifierContext) + // ExitOptExpr is called when exiting the optExpr production. ExitOptExpr(c *OptExprContext) diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_parser.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_parser.go index 35334af61..38693df58 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_parser.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_parser.go @@ -1,10 +1,10 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen // CEL import ( "fmt" "strconv" - "sync" + "sync" "github.com/antlr4-go/antlr/v4" ) @@ -14,167 +14,170 @@ var _ = fmt.Printf var _ = strconv.Itoa var _ = sync.Once{} - type CELParser struct { *antlr.BaseParser } var CELParserStaticData struct { - once sync.Once - serializedATN []int32 - LiteralNames []string - SymbolicNames []string - RuleNames []string - PredictionContextCache *antlr.PredictionContextCache - atn *antlr.ATN - decisionToDFA []*antlr.DFA + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA } func celParserInit() { - staticData := &CELParserStaticData - staticData.LiteralNames = []string{ - "", "'=='", "'!='", "'in'", "'<'", "'<='", "'>='", "'>'", "'&&'", "'||'", - "'['", "']'", "'{'", "'}'", "'('", "')'", "'.'", "','", "'-'", "'!'", - "'?'", "':'", "'+'", "'*'", "'/'", "'%'", "'true'", "'false'", "'null'", - } - staticData.SymbolicNames = []string{ - "", "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", - "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", - "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", - "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", - "NUL", "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", - "STRING", "BYTES", "IDENTIFIER", - } - staticData.RuleNames = []string{ - "start", "expr", "conditionalOr", "conditionalAnd", "relation", "calc", - "unary", "member", "primary", "exprList", "listInit", "fieldInitializerList", - "optField", "mapInitializerList", "optExpr", "literal", - } - staticData.PredictionContextCache = antlr.NewPredictionContextCache() - staticData.serializedATN = []int32{ - 4, 1, 36, 251, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, - 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, - 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, - 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 42, 8, 1, 1, - 2, 1, 2, 1, 2, 5, 2, 47, 8, 2, 10, 2, 12, 2, 50, 9, 2, 1, 3, 1, 3, 1, 3, - 5, 3, 55, 8, 3, 10, 3, 12, 3, 58, 9, 3, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, - 4, 5, 4, 66, 8, 4, 10, 4, 12, 4, 69, 9, 4, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, - 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 80, 8, 5, 10, 5, 12, 5, 83, 9, 5, 1, 6, 1, - 6, 4, 6, 87, 8, 6, 11, 6, 12, 6, 88, 1, 6, 1, 6, 4, 6, 93, 8, 6, 11, 6, - 12, 6, 94, 1, 6, 3, 6, 98, 8, 6, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, - 7, 106, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 114, 8, 7, 1, 7, - 1, 7, 1, 7, 1, 7, 3, 7, 120, 8, 7, 1, 7, 1, 7, 1, 7, 5, 7, 125, 8, 7, 10, - 7, 12, 7, 128, 9, 7, 1, 8, 3, 8, 131, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 136, - 8, 8, 1, 8, 3, 8, 139, 8, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 3, 8, - 147, 8, 8, 1, 8, 3, 8, 150, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 155, 8, 8, 1, - 8, 3, 8, 158, 8, 8, 1, 8, 1, 8, 3, 8, 162, 8, 8, 1, 8, 1, 8, 1, 8, 5, 8, - 167, 8, 8, 10, 8, 12, 8, 170, 9, 8, 1, 8, 1, 8, 3, 8, 174, 8, 8, 1, 8, - 3, 8, 177, 8, 8, 1, 8, 1, 8, 3, 8, 181, 8, 8, 1, 9, 1, 9, 1, 9, 5, 9, 186, - 8, 9, 10, 9, 12, 9, 189, 9, 9, 1, 10, 1, 10, 1, 10, 5, 10, 194, 8, 10, - 10, 10, 12, 10, 197, 9, 10, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, - 11, 1, 11, 5, 11, 207, 8, 11, 10, 11, 12, 11, 210, 9, 11, 1, 12, 3, 12, - 213, 8, 12, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, - 13, 1, 13, 5, 13, 225, 8, 13, 10, 13, 12, 13, 228, 9, 13, 1, 14, 3, 14, - 231, 8, 14, 1, 14, 1, 14, 1, 15, 3, 15, 236, 8, 15, 1, 15, 1, 15, 1, 15, - 3, 15, 241, 8, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 1, 15, 3, 15, 249, - 8, 15, 1, 15, 0, 3, 8, 10, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, - 22, 24, 26, 28, 30, 0, 3, 1, 0, 1, 7, 1, 0, 23, 25, 2, 0, 18, 18, 22, 22, - 281, 0, 32, 1, 0, 0, 0, 2, 35, 1, 0, 0, 0, 4, 43, 1, 0, 0, 0, 6, 51, 1, - 0, 0, 0, 8, 59, 1, 0, 0, 0, 10, 70, 1, 0, 0, 0, 12, 97, 1, 0, 0, 0, 14, - 99, 1, 0, 0, 0, 16, 180, 1, 0, 0, 0, 18, 182, 1, 0, 0, 0, 20, 190, 1, 0, - 0, 0, 22, 198, 1, 0, 0, 0, 24, 212, 1, 0, 0, 0, 26, 216, 1, 0, 0, 0, 28, - 230, 1, 0, 0, 0, 30, 248, 1, 0, 0, 0, 32, 33, 3, 2, 1, 0, 33, 34, 5, 0, - 0, 1, 34, 1, 1, 0, 0, 0, 35, 41, 3, 4, 2, 0, 36, 37, 5, 20, 0, 0, 37, 38, - 3, 4, 2, 0, 38, 39, 5, 21, 0, 0, 39, 40, 3, 2, 1, 0, 40, 42, 1, 0, 0, 0, - 41, 36, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 3, 1, 0, 0, 0, 43, 48, 3, 6, - 3, 0, 44, 45, 5, 9, 0, 0, 45, 47, 3, 6, 3, 0, 46, 44, 1, 0, 0, 0, 47, 50, - 1, 0, 0, 0, 48, 46, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 5, 1, 0, 0, 0, - 50, 48, 1, 0, 0, 0, 51, 56, 3, 8, 4, 0, 52, 53, 5, 8, 0, 0, 53, 55, 3, - 8, 4, 0, 54, 52, 1, 0, 0, 0, 55, 58, 1, 0, 0, 0, 56, 54, 1, 0, 0, 0, 56, - 57, 1, 0, 0, 0, 57, 7, 1, 0, 0, 0, 58, 56, 1, 0, 0, 0, 59, 60, 6, 4, -1, - 0, 60, 61, 3, 10, 5, 0, 61, 67, 1, 0, 0, 0, 62, 63, 10, 1, 0, 0, 63, 64, - 7, 0, 0, 0, 64, 66, 3, 8, 4, 2, 65, 62, 1, 0, 0, 0, 66, 69, 1, 0, 0, 0, - 67, 65, 1, 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 9, 1, 0, 0, 0, 69, 67, 1, 0, - 0, 0, 70, 71, 6, 5, -1, 0, 71, 72, 3, 12, 6, 0, 72, 81, 1, 0, 0, 0, 73, - 74, 10, 2, 0, 0, 74, 75, 7, 1, 0, 0, 75, 80, 3, 10, 5, 3, 76, 77, 10, 1, - 0, 0, 77, 78, 7, 2, 0, 0, 78, 80, 3, 10, 5, 2, 79, 73, 1, 0, 0, 0, 79, - 76, 1, 0, 0, 0, 80, 83, 1, 0, 0, 0, 81, 79, 1, 0, 0, 0, 81, 82, 1, 0, 0, - 0, 82, 11, 1, 0, 0, 0, 83, 81, 1, 0, 0, 0, 84, 98, 3, 14, 7, 0, 85, 87, - 5, 19, 0, 0, 86, 85, 1, 0, 0, 0, 87, 88, 1, 0, 0, 0, 88, 86, 1, 0, 0, 0, - 88, 89, 1, 0, 0, 0, 89, 90, 1, 0, 0, 0, 90, 98, 3, 14, 7, 0, 91, 93, 5, - 18, 0, 0, 92, 91, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 92, 1, 0, 0, 0, 94, - 95, 1, 0, 0, 0, 95, 96, 1, 0, 0, 0, 96, 98, 3, 14, 7, 0, 97, 84, 1, 0, - 0, 0, 97, 86, 1, 0, 0, 0, 97, 92, 1, 0, 0, 0, 98, 13, 1, 0, 0, 0, 99, 100, - 6, 7, -1, 0, 100, 101, 3, 16, 8, 0, 101, 126, 1, 0, 0, 0, 102, 103, 10, - 3, 0, 0, 103, 105, 5, 16, 0, 0, 104, 106, 5, 20, 0, 0, 105, 104, 1, 0, - 0, 0, 105, 106, 1, 0, 0, 0, 106, 107, 1, 0, 0, 0, 107, 125, 5, 36, 0, 0, - 108, 109, 10, 2, 0, 0, 109, 110, 5, 16, 0, 0, 110, 111, 5, 36, 0, 0, 111, - 113, 5, 14, 0, 0, 112, 114, 3, 18, 9, 0, 113, 112, 1, 0, 0, 0, 113, 114, - 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 125, 5, 15, 0, 0, 116, 117, 10, - 1, 0, 0, 117, 119, 5, 10, 0, 0, 118, 120, 5, 20, 0, 0, 119, 118, 1, 0, - 0, 0, 119, 120, 1, 0, 0, 0, 120, 121, 1, 0, 0, 0, 121, 122, 3, 2, 1, 0, - 122, 123, 5, 11, 0, 0, 123, 125, 1, 0, 0, 0, 124, 102, 1, 0, 0, 0, 124, - 108, 1, 0, 0, 0, 124, 116, 1, 0, 0, 0, 125, 128, 1, 0, 0, 0, 126, 124, - 1, 0, 0, 0, 126, 127, 1, 0, 0, 0, 127, 15, 1, 0, 0, 0, 128, 126, 1, 0, - 0, 0, 129, 131, 5, 16, 0, 0, 130, 129, 1, 0, 0, 0, 130, 131, 1, 0, 0, 0, - 131, 132, 1, 0, 0, 0, 132, 138, 5, 36, 0, 0, 133, 135, 5, 14, 0, 0, 134, - 136, 3, 18, 9, 0, 135, 134, 1, 0, 0, 0, 135, 136, 1, 0, 0, 0, 136, 137, - 1, 0, 0, 0, 137, 139, 5, 15, 0, 0, 138, 133, 1, 0, 0, 0, 138, 139, 1, 0, - 0, 0, 139, 181, 1, 0, 0, 0, 140, 141, 5, 14, 0, 0, 141, 142, 3, 2, 1, 0, - 142, 143, 5, 15, 0, 0, 143, 181, 1, 0, 0, 0, 144, 146, 5, 10, 0, 0, 145, - 147, 3, 20, 10, 0, 146, 145, 1, 0, 0, 0, 146, 147, 1, 0, 0, 0, 147, 149, - 1, 0, 0, 0, 148, 150, 5, 17, 0, 0, 149, 148, 1, 0, 0, 0, 149, 150, 1, 0, - 0, 0, 150, 151, 1, 0, 0, 0, 151, 181, 5, 11, 0, 0, 152, 154, 5, 12, 0, - 0, 153, 155, 3, 26, 13, 0, 154, 153, 1, 0, 0, 0, 154, 155, 1, 0, 0, 0, - 155, 157, 1, 0, 0, 0, 156, 158, 5, 17, 0, 0, 157, 156, 1, 0, 0, 0, 157, - 158, 1, 0, 0, 0, 158, 159, 1, 0, 0, 0, 159, 181, 5, 13, 0, 0, 160, 162, - 5, 16, 0, 0, 161, 160, 1, 0, 0, 0, 161, 162, 1, 0, 0, 0, 162, 163, 1, 0, - 0, 0, 163, 168, 5, 36, 0, 0, 164, 165, 5, 16, 0, 0, 165, 167, 5, 36, 0, - 0, 166, 164, 1, 0, 0, 0, 167, 170, 1, 0, 0, 0, 168, 166, 1, 0, 0, 0, 168, - 169, 1, 0, 0, 0, 169, 171, 1, 0, 0, 0, 170, 168, 1, 0, 0, 0, 171, 173, - 5, 12, 0, 0, 172, 174, 3, 22, 11, 0, 173, 172, 1, 0, 0, 0, 173, 174, 1, - 0, 0, 0, 174, 176, 1, 0, 0, 0, 175, 177, 5, 17, 0, 0, 176, 175, 1, 0, 0, - 0, 176, 177, 1, 0, 0, 0, 177, 178, 1, 0, 0, 0, 178, 181, 5, 13, 0, 0, 179, - 181, 3, 30, 15, 0, 180, 130, 1, 0, 0, 0, 180, 140, 1, 0, 0, 0, 180, 144, - 1, 0, 0, 0, 180, 152, 1, 0, 0, 0, 180, 161, 1, 0, 0, 0, 180, 179, 1, 0, - 0, 0, 181, 17, 1, 0, 0, 0, 182, 187, 3, 2, 1, 0, 183, 184, 5, 17, 0, 0, - 184, 186, 3, 2, 1, 0, 185, 183, 1, 0, 0, 0, 186, 189, 1, 0, 0, 0, 187, - 185, 1, 0, 0, 0, 187, 188, 1, 0, 0, 0, 188, 19, 1, 0, 0, 0, 189, 187, 1, - 0, 0, 0, 190, 195, 3, 28, 14, 0, 191, 192, 5, 17, 0, 0, 192, 194, 3, 28, - 14, 0, 193, 191, 1, 0, 0, 0, 194, 197, 1, 0, 0, 0, 195, 193, 1, 0, 0, 0, - 195, 196, 1, 0, 0, 0, 196, 21, 1, 0, 0, 0, 197, 195, 1, 0, 0, 0, 198, 199, - 3, 24, 12, 0, 199, 200, 5, 21, 0, 0, 200, 208, 3, 2, 1, 0, 201, 202, 5, - 17, 0, 0, 202, 203, 3, 24, 12, 0, 203, 204, 5, 21, 0, 0, 204, 205, 3, 2, - 1, 0, 205, 207, 1, 0, 0, 0, 206, 201, 1, 0, 0, 0, 207, 210, 1, 0, 0, 0, - 208, 206, 1, 0, 0, 0, 208, 209, 1, 0, 0, 0, 209, 23, 1, 0, 0, 0, 210, 208, - 1, 0, 0, 0, 211, 213, 5, 20, 0, 0, 212, 211, 1, 0, 0, 0, 212, 213, 1, 0, - 0, 0, 213, 214, 1, 0, 0, 0, 214, 215, 5, 36, 0, 0, 215, 25, 1, 0, 0, 0, - 216, 217, 3, 28, 14, 0, 217, 218, 5, 21, 0, 0, 218, 226, 3, 2, 1, 0, 219, - 220, 5, 17, 0, 0, 220, 221, 3, 28, 14, 0, 221, 222, 5, 21, 0, 0, 222, 223, - 3, 2, 1, 0, 223, 225, 1, 0, 0, 0, 224, 219, 1, 0, 0, 0, 225, 228, 1, 0, - 0, 0, 226, 224, 1, 0, 0, 0, 226, 227, 1, 0, 0, 0, 227, 27, 1, 0, 0, 0, - 228, 226, 1, 0, 0, 0, 229, 231, 5, 20, 0, 0, 230, 229, 1, 0, 0, 0, 230, - 231, 1, 0, 0, 0, 231, 232, 1, 0, 0, 0, 232, 233, 3, 2, 1, 0, 233, 29, 1, - 0, 0, 0, 234, 236, 5, 18, 0, 0, 235, 234, 1, 0, 0, 0, 235, 236, 1, 0, 0, - 0, 236, 237, 1, 0, 0, 0, 237, 249, 5, 32, 0, 0, 238, 249, 5, 33, 0, 0, - 239, 241, 5, 18, 0, 0, 240, 239, 1, 0, 0, 0, 240, 241, 1, 0, 0, 0, 241, - 242, 1, 0, 0, 0, 242, 249, 5, 31, 0, 0, 243, 249, 5, 34, 0, 0, 244, 249, - 5, 35, 0, 0, 245, 249, 5, 26, 0, 0, 246, 249, 5, 27, 0, 0, 247, 249, 5, - 28, 0, 0, 248, 235, 1, 0, 0, 0, 248, 238, 1, 0, 0, 0, 248, 240, 1, 0, 0, - 0, 248, 243, 1, 0, 0, 0, 248, 244, 1, 0, 0, 0, 248, 245, 1, 0, 0, 0, 248, - 246, 1, 0, 0, 0, 248, 247, 1, 0, 0, 0, 249, 31, 1, 0, 0, 0, 35, 41, 48, - 56, 67, 79, 81, 88, 94, 97, 105, 113, 119, 124, 126, 130, 135, 138, 146, - 149, 154, 157, 161, 168, 173, 176, 180, 187, 195, 208, 212, 226, 230, 235, - 240, 248, -} - deserializer := antlr.NewATNDeserializer(nil) - staticData.atn = deserializer.Deserialize(staticData.serializedATN) - atn := staticData.atn - staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) - decisionToDFA := staticData.decisionToDFA - for index, state := range atn.DecisionToState { - decisionToDFA[index] = antlr.NewDFA(state, index) - } + staticData := &CELParserStaticData + staticData.LiteralNames = []string{ + "", "'=='", "'!='", "'in'", "'<'", "'<='", "'>='", "'>'", "'&&'", "'||'", + "'['", "']'", "'{'", "'}'", "'('", "')'", "'.'", "','", "'-'", "'!'", + "'?'", "':'", "'+'", "'*'", "'/'", "'%'", "'true'", "'false'", "'null'", + } + staticData.SymbolicNames = []string{ + "", "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS", + "GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE", + "RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK", + "COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE", + "NUL", "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", + "STRING", "BYTES", "IDENTIFIER", "ESC_IDENTIFIER", + } + staticData.RuleNames = []string{ + "start", "expr", "conditionalOr", "conditionalAnd", "relation", "calc", + "unary", "member", "primary", "exprList", "listInit", "fieldInitializerList", + "optField", "mapInitializerList", "escapeIdent", "optExpr", "literal", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 37, 259, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, + 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, + 2, 16, 7, 16, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, + 1, 44, 8, 1, 1, 2, 1, 2, 1, 2, 5, 2, 49, 8, 2, 10, 2, 12, 2, 52, 9, 2, + 1, 3, 1, 3, 1, 3, 5, 3, 57, 8, 3, 10, 3, 12, 3, 60, 9, 3, 1, 4, 1, 4, 1, + 4, 1, 4, 1, 4, 1, 4, 5, 4, 68, 8, 4, 10, 4, 12, 4, 71, 9, 4, 1, 5, 1, 5, + 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 5, 5, 82, 8, 5, 10, 5, 12, 5, + 85, 9, 5, 1, 6, 1, 6, 4, 6, 89, 8, 6, 11, 6, 12, 6, 90, 1, 6, 1, 6, 4, + 6, 95, 8, 6, 11, 6, 12, 6, 96, 1, 6, 3, 6, 100, 8, 6, 1, 7, 1, 7, 1, 7, + 1, 7, 1, 7, 1, 7, 3, 7, 108, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, 1, 7, + 3, 7, 116, 8, 7, 1, 7, 1, 7, 1, 7, 1, 7, 3, 7, 122, 8, 7, 1, 7, 1, 7, 1, + 7, 5, 7, 127, 8, 7, 10, 7, 12, 7, 130, 9, 7, 1, 8, 3, 8, 133, 8, 8, 1, + 8, 1, 8, 3, 8, 137, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 142, 8, 8, 1, 8, 1, 8, + 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 3, 8, 151, 8, 8, 1, 8, 3, 8, 154, 8, 8, 1, + 8, 1, 8, 1, 8, 3, 8, 159, 8, 8, 1, 8, 3, 8, 162, 8, 8, 1, 8, 1, 8, 3, 8, + 166, 8, 8, 1, 8, 1, 8, 1, 8, 5, 8, 171, 8, 8, 10, 8, 12, 8, 174, 9, 8, + 1, 8, 1, 8, 3, 8, 178, 8, 8, 1, 8, 3, 8, 181, 8, 8, 1, 8, 1, 8, 3, 8, 185, + 8, 8, 1, 9, 1, 9, 1, 9, 5, 9, 190, 8, 9, 10, 9, 12, 9, 193, 9, 9, 1, 10, + 1, 10, 1, 10, 5, 10, 198, 8, 10, 10, 10, 12, 10, 201, 9, 10, 1, 11, 1, + 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 1, 11, 5, 11, 211, 8, 11, 10, 11, + 12, 11, 214, 9, 11, 1, 12, 3, 12, 217, 8, 12, 1, 12, 1, 12, 1, 13, 1, 13, + 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 1, 13, 5, 13, 229, 8, 13, 10, 13, 12, + 13, 232, 9, 13, 1, 14, 1, 14, 3, 14, 236, 8, 14, 1, 15, 3, 15, 239, 8, + 15, 1, 15, 1, 15, 1, 16, 3, 16, 244, 8, 16, 1, 16, 1, 16, 1, 16, 3, 16, + 249, 8, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 1, 16, 3, 16, 257, 8, 16, + 1, 16, 0, 3, 8, 10, 14, 17, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, + 24, 26, 28, 30, 32, 0, 3, 1, 0, 1, 7, 1, 0, 23, 25, 2, 0, 18, 18, 22, 22, + 290, 0, 34, 1, 0, 0, 0, 2, 37, 1, 0, 0, 0, 4, 45, 1, 0, 0, 0, 6, 53, 1, + 0, 0, 0, 8, 61, 1, 0, 0, 0, 10, 72, 1, 0, 0, 0, 12, 99, 1, 0, 0, 0, 14, + 101, 1, 0, 0, 0, 16, 184, 1, 0, 0, 0, 18, 186, 1, 0, 0, 0, 20, 194, 1, + 0, 0, 0, 22, 202, 1, 0, 0, 0, 24, 216, 1, 0, 0, 0, 26, 220, 1, 0, 0, 0, + 28, 235, 1, 0, 0, 0, 30, 238, 1, 0, 0, 0, 32, 256, 1, 0, 0, 0, 34, 35, + 3, 2, 1, 0, 35, 36, 5, 0, 0, 1, 36, 1, 1, 0, 0, 0, 37, 43, 3, 4, 2, 0, + 38, 39, 5, 20, 0, 0, 39, 40, 3, 4, 2, 0, 40, 41, 5, 21, 0, 0, 41, 42, 3, + 2, 1, 0, 42, 44, 1, 0, 0, 0, 43, 38, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, + 3, 1, 0, 0, 0, 45, 50, 3, 6, 3, 0, 46, 47, 5, 9, 0, 0, 47, 49, 3, 6, 3, + 0, 48, 46, 1, 0, 0, 0, 49, 52, 1, 0, 0, 0, 50, 48, 1, 0, 0, 0, 50, 51, + 1, 0, 0, 0, 51, 5, 1, 0, 0, 0, 52, 50, 1, 0, 0, 0, 53, 58, 3, 8, 4, 0, + 54, 55, 5, 8, 0, 0, 55, 57, 3, 8, 4, 0, 56, 54, 1, 0, 0, 0, 57, 60, 1, + 0, 0, 0, 58, 56, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 7, 1, 0, 0, 0, 60, + 58, 1, 0, 0, 0, 61, 62, 6, 4, -1, 0, 62, 63, 3, 10, 5, 0, 63, 69, 1, 0, + 0, 0, 64, 65, 10, 1, 0, 0, 65, 66, 7, 0, 0, 0, 66, 68, 3, 8, 4, 2, 67, + 64, 1, 0, 0, 0, 68, 71, 1, 0, 0, 0, 69, 67, 1, 0, 0, 0, 69, 70, 1, 0, 0, + 0, 70, 9, 1, 0, 0, 0, 71, 69, 1, 0, 0, 0, 72, 73, 6, 5, -1, 0, 73, 74, + 3, 12, 6, 0, 74, 83, 1, 0, 0, 0, 75, 76, 10, 2, 0, 0, 76, 77, 7, 1, 0, + 0, 77, 82, 3, 10, 5, 3, 78, 79, 10, 1, 0, 0, 79, 80, 7, 2, 0, 0, 80, 82, + 3, 10, 5, 2, 81, 75, 1, 0, 0, 0, 81, 78, 1, 0, 0, 0, 82, 85, 1, 0, 0, 0, + 83, 81, 1, 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 11, 1, 0, 0, 0, 85, 83, 1, + 0, 0, 0, 86, 100, 3, 14, 7, 0, 87, 89, 5, 19, 0, 0, 88, 87, 1, 0, 0, 0, + 89, 90, 1, 0, 0, 0, 90, 88, 1, 0, 0, 0, 90, 91, 1, 0, 0, 0, 91, 92, 1, + 0, 0, 0, 92, 100, 3, 14, 7, 0, 93, 95, 5, 18, 0, 0, 94, 93, 1, 0, 0, 0, + 95, 96, 1, 0, 0, 0, 96, 94, 1, 0, 0, 0, 96, 97, 1, 0, 0, 0, 97, 98, 1, + 0, 0, 0, 98, 100, 3, 14, 7, 0, 99, 86, 1, 0, 0, 0, 99, 88, 1, 0, 0, 0, + 99, 94, 1, 0, 0, 0, 100, 13, 1, 0, 0, 0, 101, 102, 6, 7, -1, 0, 102, 103, + 3, 16, 8, 0, 103, 128, 1, 0, 0, 0, 104, 105, 10, 3, 0, 0, 105, 107, 5, + 16, 0, 0, 106, 108, 5, 20, 0, 0, 107, 106, 1, 0, 0, 0, 107, 108, 1, 0, + 0, 0, 108, 109, 1, 0, 0, 0, 109, 127, 3, 28, 14, 0, 110, 111, 10, 2, 0, + 0, 111, 112, 5, 16, 0, 0, 112, 113, 5, 36, 0, 0, 113, 115, 5, 14, 0, 0, + 114, 116, 3, 18, 9, 0, 115, 114, 1, 0, 0, 0, 115, 116, 1, 0, 0, 0, 116, + 117, 1, 0, 0, 0, 117, 127, 5, 15, 0, 0, 118, 119, 10, 1, 0, 0, 119, 121, + 5, 10, 0, 0, 120, 122, 5, 20, 0, 0, 121, 120, 1, 0, 0, 0, 121, 122, 1, + 0, 0, 0, 122, 123, 1, 0, 0, 0, 123, 124, 3, 2, 1, 0, 124, 125, 5, 11, 0, + 0, 125, 127, 1, 0, 0, 0, 126, 104, 1, 0, 0, 0, 126, 110, 1, 0, 0, 0, 126, + 118, 1, 0, 0, 0, 127, 130, 1, 0, 0, 0, 128, 126, 1, 0, 0, 0, 128, 129, + 1, 0, 0, 0, 129, 15, 1, 0, 0, 0, 130, 128, 1, 0, 0, 0, 131, 133, 5, 16, + 0, 0, 132, 131, 1, 0, 0, 0, 132, 133, 1, 0, 0, 0, 133, 134, 1, 0, 0, 0, + 134, 185, 5, 36, 0, 0, 135, 137, 5, 16, 0, 0, 136, 135, 1, 0, 0, 0, 136, + 137, 1, 0, 0, 0, 137, 138, 1, 0, 0, 0, 138, 139, 5, 36, 0, 0, 139, 141, + 5, 14, 0, 0, 140, 142, 3, 18, 9, 0, 141, 140, 1, 0, 0, 0, 141, 142, 1, + 0, 0, 0, 142, 143, 1, 0, 0, 0, 143, 185, 5, 15, 0, 0, 144, 145, 5, 14, + 0, 0, 145, 146, 3, 2, 1, 0, 146, 147, 5, 15, 0, 0, 147, 185, 1, 0, 0, 0, + 148, 150, 5, 10, 0, 0, 149, 151, 3, 20, 10, 0, 150, 149, 1, 0, 0, 0, 150, + 151, 1, 0, 0, 0, 151, 153, 1, 0, 0, 0, 152, 154, 5, 17, 0, 0, 153, 152, + 1, 0, 0, 0, 153, 154, 1, 0, 0, 0, 154, 155, 1, 0, 0, 0, 155, 185, 5, 11, + 0, 0, 156, 158, 5, 12, 0, 0, 157, 159, 3, 26, 13, 0, 158, 157, 1, 0, 0, + 0, 158, 159, 1, 0, 0, 0, 159, 161, 1, 0, 0, 0, 160, 162, 5, 17, 0, 0, 161, + 160, 1, 0, 0, 0, 161, 162, 1, 0, 0, 0, 162, 163, 1, 0, 0, 0, 163, 185, + 5, 13, 0, 0, 164, 166, 5, 16, 0, 0, 165, 164, 1, 0, 0, 0, 165, 166, 1, + 0, 0, 0, 166, 167, 1, 0, 0, 0, 167, 172, 5, 36, 0, 0, 168, 169, 5, 16, + 0, 0, 169, 171, 5, 36, 0, 0, 170, 168, 1, 0, 0, 0, 171, 174, 1, 0, 0, 0, + 172, 170, 1, 0, 0, 0, 172, 173, 1, 0, 0, 0, 173, 175, 1, 0, 0, 0, 174, + 172, 1, 0, 0, 0, 175, 177, 5, 12, 0, 0, 176, 178, 3, 22, 11, 0, 177, 176, + 1, 0, 0, 0, 177, 178, 1, 0, 0, 0, 178, 180, 1, 0, 0, 0, 179, 181, 5, 17, + 0, 0, 180, 179, 1, 0, 0, 0, 180, 181, 1, 0, 0, 0, 181, 182, 1, 0, 0, 0, + 182, 185, 5, 13, 0, 0, 183, 185, 3, 32, 16, 0, 184, 132, 1, 0, 0, 0, 184, + 136, 1, 0, 0, 0, 184, 144, 1, 0, 0, 0, 184, 148, 1, 0, 0, 0, 184, 156, + 1, 0, 0, 0, 184, 165, 1, 0, 0, 0, 184, 183, 1, 0, 0, 0, 185, 17, 1, 0, + 0, 0, 186, 191, 3, 2, 1, 0, 187, 188, 5, 17, 0, 0, 188, 190, 3, 2, 1, 0, + 189, 187, 1, 0, 0, 0, 190, 193, 1, 0, 0, 0, 191, 189, 1, 0, 0, 0, 191, + 192, 1, 0, 0, 0, 192, 19, 1, 0, 0, 0, 193, 191, 1, 0, 0, 0, 194, 199, 3, + 30, 15, 0, 195, 196, 5, 17, 0, 0, 196, 198, 3, 30, 15, 0, 197, 195, 1, + 0, 0, 0, 198, 201, 1, 0, 0, 0, 199, 197, 1, 0, 0, 0, 199, 200, 1, 0, 0, + 0, 200, 21, 1, 0, 0, 0, 201, 199, 1, 0, 0, 0, 202, 203, 3, 24, 12, 0, 203, + 204, 5, 21, 0, 0, 204, 212, 3, 2, 1, 0, 205, 206, 5, 17, 0, 0, 206, 207, + 3, 24, 12, 0, 207, 208, 5, 21, 0, 0, 208, 209, 3, 2, 1, 0, 209, 211, 1, + 0, 0, 0, 210, 205, 1, 0, 0, 0, 211, 214, 1, 0, 0, 0, 212, 210, 1, 0, 0, + 0, 212, 213, 1, 0, 0, 0, 213, 23, 1, 0, 0, 0, 214, 212, 1, 0, 0, 0, 215, + 217, 5, 20, 0, 0, 216, 215, 1, 0, 0, 0, 216, 217, 1, 0, 0, 0, 217, 218, + 1, 0, 0, 0, 218, 219, 3, 28, 14, 0, 219, 25, 1, 0, 0, 0, 220, 221, 3, 30, + 15, 0, 221, 222, 5, 21, 0, 0, 222, 230, 3, 2, 1, 0, 223, 224, 5, 17, 0, + 0, 224, 225, 3, 30, 15, 0, 225, 226, 5, 21, 0, 0, 226, 227, 3, 2, 1, 0, + 227, 229, 1, 0, 0, 0, 228, 223, 1, 0, 0, 0, 229, 232, 1, 0, 0, 0, 230, + 228, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 27, 1, 0, 0, 0, 232, 230, 1, + 0, 0, 0, 233, 236, 5, 36, 0, 0, 234, 236, 5, 37, 0, 0, 235, 233, 1, 0, + 0, 0, 235, 234, 1, 0, 0, 0, 236, 29, 1, 0, 0, 0, 237, 239, 5, 20, 0, 0, + 238, 237, 1, 0, 0, 0, 238, 239, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, + 241, 3, 2, 1, 0, 241, 31, 1, 0, 0, 0, 242, 244, 5, 18, 0, 0, 243, 242, + 1, 0, 0, 0, 243, 244, 1, 0, 0, 0, 244, 245, 1, 0, 0, 0, 245, 257, 5, 32, + 0, 0, 246, 257, 5, 33, 0, 0, 247, 249, 5, 18, 0, 0, 248, 247, 1, 0, 0, + 0, 248, 249, 1, 0, 0, 0, 249, 250, 1, 0, 0, 0, 250, 257, 5, 31, 0, 0, 251, + 257, 5, 34, 0, 0, 252, 257, 5, 35, 0, 0, 253, 257, 5, 26, 0, 0, 254, 257, + 5, 27, 0, 0, 255, 257, 5, 28, 0, 0, 256, 243, 1, 0, 0, 0, 256, 246, 1, + 0, 0, 0, 256, 248, 1, 0, 0, 0, 256, 251, 1, 0, 0, 0, 256, 252, 1, 0, 0, + 0, 256, 253, 1, 0, 0, 0, 256, 254, 1, 0, 0, 0, 256, 255, 1, 0, 0, 0, 257, + 33, 1, 0, 0, 0, 36, 43, 50, 58, 69, 81, 83, 90, 96, 99, 107, 115, 121, + 126, 128, 132, 136, 141, 150, 153, 158, 161, 165, 172, 177, 180, 184, 191, + 199, 212, 216, 230, 235, 238, 243, 248, 256, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } } // CELParserInit initializes any static state used to implement CELParser. By default the @@ -182,8 +185,8 @@ func celParserInit() { // NewCELParser(). You can call this function if you wish to initialize the static state ahead // of time. func CELParserInit() { - staticData := &CELParserStaticData - staticData.once.Do(celParserInit) + staticData := &CELParserStaticData + staticData.once.Do(celParserInit) } // NewCELParser produces a new parser instance for the optional input antlr.TokenStream. @@ -191,7 +194,7 @@ func NewCELParser(input antlr.TokenStream) *CELParser { CELParserInit() this := new(CELParser) this.BaseParser = antlr.NewBaseParser(input) - staticData := &CELParserStaticData + staticData := &CELParserStaticData this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) this.RuleNames = staticData.RuleNames this.LiteralNames = staticData.LiteralNames @@ -201,66 +204,67 @@ func NewCELParser(input antlr.TokenStream) *CELParser { return this } - // CELParser tokens. const ( - CELParserEOF = antlr.TokenEOF - CELParserEQUALS = 1 - CELParserNOT_EQUALS = 2 - CELParserIN = 3 - CELParserLESS = 4 - CELParserLESS_EQUALS = 5 + CELParserEOF = antlr.TokenEOF + CELParserEQUALS = 1 + CELParserNOT_EQUALS = 2 + CELParserIN = 3 + CELParserLESS = 4 + CELParserLESS_EQUALS = 5 CELParserGREATER_EQUALS = 6 - CELParserGREATER = 7 - CELParserLOGICAL_AND = 8 - CELParserLOGICAL_OR = 9 - CELParserLBRACKET = 10 - CELParserRPRACKET = 11 - CELParserLBRACE = 12 - CELParserRBRACE = 13 - CELParserLPAREN = 14 - CELParserRPAREN = 15 - CELParserDOT = 16 - CELParserCOMMA = 17 - CELParserMINUS = 18 - CELParserEXCLAM = 19 - CELParserQUESTIONMARK = 20 - CELParserCOLON = 21 - CELParserPLUS = 22 - CELParserSTAR = 23 - CELParserSLASH = 24 - CELParserPERCENT = 25 - CELParserCEL_TRUE = 26 - CELParserCEL_FALSE = 27 - CELParserNUL = 28 - CELParserWHITESPACE = 29 - CELParserCOMMENT = 30 - CELParserNUM_FLOAT = 31 - CELParserNUM_INT = 32 - CELParserNUM_UINT = 33 - CELParserSTRING = 34 - CELParserBYTES = 35 - CELParserIDENTIFIER = 36 + CELParserGREATER = 7 + CELParserLOGICAL_AND = 8 + CELParserLOGICAL_OR = 9 + CELParserLBRACKET = 10 + CELParserRPRACKET = 11 + CELParserLBRACE = 12 + CELParserRBRACE = 13 + CELParserLPAREN = 14 + CELParserRPAREN = 15 + CELParserDOT = 16 + CELParserCOMMA = 17 + CELParserMINUS = 18 + CELParserEXCLAM = 19 + CELParserQUESTIONMARK = 20 + CELParserCOLON = 21 + CELParserPLUS = 22 + CELParserSTAR = 23 + CELParserSLASH = 24 + CELParserPERCENT = 25 + CELParserCEL_TRUE = 26 + CELParserCEL_FALSE = 27 + CELParserNUL = 28 + CELParserWHITESPACE = 29 + CELParserCOMMENT = 30 + CELParserNUM_FLOAT = 31 + CELParserNUM_INT = 32 + CELParserNUM_UINT = 33 + CELParserSTRING = 34 + CELParserBYTES = 35 + CELParserIDENTIFIER = 36 + CELParserESC_IDENTIFIER = 37 ) // CELParser rules. const ( - CELParserRULE_start = 0 - CELParserRULE_expr = 1 - CELParserRULE_conditionalOr = 2 - CELParserRULE_conditionalAnd = 3 - CELParserRULE_relation = 4 - CELParserRULE_calc = 5 - CELParserRULE_unary = 6 - CELParserRULE_member = 7 - CELParserRULE_primary = 8 - CELParserRULE_exprList = 9 - CELParserRULE_listInit = 10 + CELParserRULE_start = 0 + CELParserRULE_expr = 1 + CELParserRULE_conditionalOr = 2 + CELParserRULE_conditionalAnd = 3 + CELParserRULE_relation = 4 + CELParserRULE_calc = 5 + CELParserRULE_unary = 6 + CELParserRULE_member = 7 + CELParserRULE_primary = 8 + CELParserRULE_exprList = 9 + CELParserRULE_listInit = 10 CELParserRULE_fieldInitializerList = 11 - CELParserRULE_optField = 12 - CELParserRULE_mapInitializerList = 13 - CELParserRULE_optExpr = 14 - CELParserRULE_literal = 15 + CELParserRULE_optField = 12 + CELParserRULE_mapInitializerList = 13 + CELParserRULE_escapeIdent = 14 + CELParserRULE_optExpr = 15 + CELParserRULE_literal = 16 ) // IStartContext is an interface to support dynamic dispatch. @@ -273,11 +277,9 @@ type IStartContext interface { // GetE returns the e rule contexts. GetE() IExprContext - // SetE sets the e rule contexts. SetE(IExprContext) - // Getter signatures EOF() antlr.TerminalNode Expr() IExprContext @@ -289,7 +291,7 @@ type IStartContext interface { type StartContext struct { antlr.BaseParserRuleContext parser antlr.Parser - e IExprContext + e IExprContext } func NewEmptyStartContext() *StartContext { @@ -299,7 +301,7 @@ func NewEmptyStartContext() *StartContext { return p } -func InitEmptyStartContext(p *StartContext) { +func InitEmptyStartContext(p *StartContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_start } @@ -321,19 +323,17 @@ func (s *StartContext) GetParser() antlr.Parser { return s.parser } func (s *StartContext) GetE() IExprContext { return s.e } - func (s *StartContext) SetE(v IExprContext) { s.e = v } - func (s *StartContext) EOF() antlr.TerminalNode { return s.GetToken(CELParserEOF, 0) } func (s *StartContext) Expr() IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -353,7 +353,6 @@ func (s *StartContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *StartContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterStart(s) @@ -376,32 +375,26 @@ func (s *StartContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) Start_() (localctx IStartContext) { localctx = NewStartContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 0, CELParserRULE_start) p.EnterOuterAlt(localctx, 1) { - p.SetState(32) + p.SetState(34) var _x = p.Expr() - localctx.(*StartContext).e = _x } { - p.SetState(33) + p.SetState(35) p.Match(CELParserEOF) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - - errorExit: if p.HasError() { v := p.GetError() @@ -415,7 +408,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IExprContext is an interface to support dynamic dispatch. type IExprContext interface { antlr.ParserRuleContext @@ -424,12 +416,10 @@ type IExprContext interface { GetParser() antlr.Parser // GetOp returns the op token. - GetOp() antlr.Token - + GetOp() antlr.Token // SetOp sets the op token. - SetOp(antlr.Token) - + SetOp(antlr.Token) // GetE returns the e rule contexts. GetE() IConditionalOrContext @@ -440,7 +430,6 @@ type IExprContext interface { // GetE2 returns the e2 rule contexts. GetE2() IExprContext - // SetE sets the e rule contexts. SetE(IConditionalOrContext) @@ -450,7 +439,6 @@ type IExprContext interface { // SetE2 sets the e2 rule contexts. SetE2(IExprContext) - // Getter signatures AllConditionalOr() []IConditionalOrContext ConditionalOr(i int) IConditionalOrContext @@ -465,10 +453,10 @@ type IExprContext interface { type ExprContext struct { antlr.BaseParserRuleContext parser antlr.Parser - e IConditionalOrContext - op antlr.Token - e1 IConditionalOrContext - e2 IExprContext + e IConditionalOrContext + op antlr.Token + e1 IConditionalOrContext + e2 IExprContext } func NewEmptyExprContext() *ExprContext { @@ -478,7 +466,7 @@ func NewEmptyExprContext() *ExprContext { return p } -func InitEmptyExprContext(p *ExprContext) { +func InitEmptyExprContext(p *ExprContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_expr } @@ -500,24 +488,20 @@ func (s *ExprContext) GetParser() antlr.Parser { return s.parser } func (s *ExprContext) GetOp() antlr.Token { return s.op } - func (s *ExprContext) SetOp(v antlr.Token) { s.op = v } - func (s *ExprContext) GetE() IConditionalOrContext { return s.e } func (s *ExprContext) GetE1() IConditionalOrContext { return s.e1 } func (s *ExprContext) GetE2() IExprContext { return s.e2 } - func (s *ExprContext) SetE(v IConditionalOrContext) { s.e = v } func (s *ExprContext) SetE1(v IConditionalOrContext) { s.e1 = v } func (s *ExprContext) SetE2(v IExprContext) { s.e2 = v } - func (s *ExprContext) AllConditionalOr() []IConditionalOrContext { children := s.GetChildren() len := 0 @@ -540,12 +524,12 @@ func (s *ExprContext) AllConditionalOr() []IConditionalOrContext { } func (s *ExprContext) ConditionalOr(i int) IConditionalOrContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IConditionalOrContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -568,10 +552,10 @@ func (s *ExprContext) QUESTIONMARK() antlr.TerminalNode { } func (s *ExprContext) Expr() IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -591,7 +575,6 @@ func (s *ExprContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) s return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *ExprContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterExpr(s) @@ -614,9 +597,6 @@ func (s *ExprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) Expr() (localctx IExprContext) { localctx = NewExprContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 2, CELParserRULE_expr) @@ -624,62 +604,56 @@ func (p *CELParser) Expr() (localctx IExprContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(35) + p.SetState(37) var _x = p.ConditionalOr() - localctx.(*ExprContext).e = _x } - p.SetState(41) + p.SetState(43) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserQUESTIONMARK { { - p.SetState(36) + p.SetState(38) var _m = p.Match(CELParserQUESTIONMARK) localctx.(*ExprContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - { - p.SetState(37) - - var _x = p.ConditionalOr() - - - localctx.(*ExprContext).e1 = _x - } - { - p.SetState(38) - p.Match(CELParserCOLON) - if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { p.SetState(39) - var _x = p.Expr() + var _x = p.ConditionalOr() + localctx.(*ExprContext).e1 = _x + } + { + p.SetState(40) + p.Match(CELParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(41) + + var _x = p.Expr() localctx.(*ExprContext).e2 = _x } } - - errorExit: if p.HasError() { v := p.GetError() @@ -693,7 +667,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IConditionalOrContext is an interface to support dynamic dispatch. type IConditionalOrContext interface { antlr.ParserRuleContext @@ -702,42 +675,34 @@ type IConditionalOrContext interface { GetParser() antlr.Parser // GetS9 returns the s9 token. - GetS9() antlr.Token - + GetS9() antlr.Token // SetS9 sets the s9 token. - SetS9(antlr.Token) - + SetS9(antlr.Token) // GetOps returns the ops token list. GetOps() []antlr.Token - // SetOps sets the ops token list. SetOps([]antlr.Token) - // GetE returns the e rule contexts. GetE() IConditionalAndContext // Get_conditionalAnd returns the _conditionalAnd rule contexts. Get_conditionalAnd() IConditionalAndContext - // SetE sets the e rule contexts. SetE(IConditionalAndContext) // Set_conditionalAnd sets the _conditionalAnd rule contexts. Set_conditionalAnd(IConditionalAndContext) - // GetE1 returns the e1 rule context list. GetE1() []IConditionalAndContext - // SetE1 sets the e1 rule context list. - SetE1([]IConditionalAndContext) - + SetE1([]IConditionalAndContext) // Getter signatures AllConditionalAnd() []IConditionalAndContext @@ -751,12 +716,12 @@ type IConditionalOrContext interface { type ConditionalOrContext struct { antlr.BaseParserRuleContext - parser antlr.Parser - e IConditionalAndContext - s9 antlr.Token - ops []antlr.Token - _conditionalAnd IConditionalAndContext - e1 []IConditionalAndContext + parser antlr.Parser + e IConditionalAndContext + s9 antlr.Token + ops []antlr.Token + _conditionalAnd IConditionalAndContext + e1 []IConditionalAndContext } func NewEmptyConditionalOrContext() *ConditionalOrContext { @@ -766,7 +731,7 @@ func NewEmptyConditionalOrContext() *ConditionalOrContext { return p } -func InitEmptyConditionalOrContext(p *ConditionalOrContext) { +func InitEmptyConditionalOrContext(p *ConditionalOrContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_conditionalOr } @@ -788,32 +753,24 @@ func (s *ConditionalOrContext) GetParser() antlr.Parser { return s.parser } func (s *ConditionalOrContext) GetS9() antlr.Token { return s.s9 } - func (s *ConditionalOrContext) SetS9(v antlr.Token) { s.s9 = v } - func (s *ConditionalOrContext) GetOps() []antlr.Token { return s.ops } - func (s *ConditionalOrContext) SetOps(v []antlr.Token) { s.ops = v } - func (s *ConditionalOrContext) GetE() IConditionalAndContext { return s.e } func (s *ConditionalOrContext) Get_conditionalAnd() IConditionalAndContext { return s._conditionalAnd } - func (s *ConditionalOrContext) SetE(v IConditionalAndContext) { s.e = v } func (s *ConditionalOrContext) Set_conditionalAnd(v IConditionalAndContext) { s._conditionalAnd = v } - func (s *ConditionalOrContext) GetE1() []IConditionalAndContext { return s.e1 } - func (s *ConditionalOrContext) SetE1(v []IConditionalAndContext) { s.e1 = v } - func (s *ConditionalOrContext) AllConditionalAnd() []IConditionalAndContext { children := s.GetChildren() len := 0 @@ -836,12 +793,12 @@ func (s *ConditionalOrContext) AllConditionalAnd() []IConditionalAndContext { } func (s *ConditionalOrContext) ConditionalAnd(i int) IConditionalAndContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IConditionalAndContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -871,7 +828,6 @@ func (s *ConditionalOrContext) ToStringTree(ruleNames []string, recog antlr.Reco return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *ConditionalOrContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterConditionalOr(s) @@ -894,9 +850,6 @@ func (s *ConditionalOrContext) Accept(visitor antlr.ParseTreeVisitor) interface{ } } - - - func (p *CELParser) ConditionalOr() (localctx IConditionalOrContext) { localctx = NewConditionalOrContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 4, CELParserRULE_conditionalOr) @@ -904,55 +857,49 @@ func (p *CELParser) ConditionalOr() (localctx IConditionalOrContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(43) + p.SetState(45) var _x = p.ConditionalAnd() - localctx.(*ConditionalOrContext).e = _x } - p.SetState(48) + p.SetState(50) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for _la == CELParserLOGICAL_OR { { - p.SetState(44) + p.SetState(46) var _m = p.Match(CELParserLOGICAL_OR) localctx.(*ConditionalOrContext).s9 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*ConditionalOrContext).ops = append(localctx.(*ConditionalOrContext).ops, localctx.(*ConditionalOrContext).s9) { - p.SetState(45) + p.SetState(47) var _x = p.ConditionalAnd() - localctx.(*ConditionalOrContext)._conditionalAnd = _x } localctx.(*ConditionalOrContext).e1 = append(localctx.(*ConditionalOrContext).e1, localctx.(*ConditionalOrContext)._conditionalAnd) - - p.SetState(50) + p.SetState(52) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _la = p.GetTokenStream().LA(1) } - - errorExit: if p.HasError() { v := p.GetError() @@ -966,7 +913,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IConditionalAndContext is an interface to support dynamic dispatch. type IConditionalAndContext interface { antlr.ParserRuleContext @@ -975,42 +921,34 @@ type IConditionalAndContext interface { GetParser() antlr.Parser // GetS8 returns the s8 token. - GetS8() antlr.Token - + GetS8() antlr.Token // SetS8 sets the s8 token. - SetS8(antlr.Token) - + SetS8(antlr.Token) // GetOps returns the ops token list. GetOps() []antlr.Token - // SetOps sets the ops token list. SetOps([]antlr.Token) - // GetE returns the e rule contexts. GetE() IRelationContext // Get_relation returns the _relation rule contexts. Get_relation() IRelationContext - // SetE sets the e rule contexts. SetE(IRelationContext) // Set_relation sets the _relation rule contexts. Set_relation(IRelationContext) - // GetE1 returns the e1 rule context list. GetE1() []IRelationContext - // SetE1 sets the e1 rule context list. - SetE1([]IRelationContext) - + SetE1([]IRelationContext) // Getter signatures AllRelation() []IRelationContext @@ -1024,12 +962,12 @@ type IConditionalAndContext interface { type ConditionalAndContext struct { antlr.BaseParserRuleContext - parser antlr.Parser - e IRelationContext - s8 antlr.Token - ops []antlr.Token - _relation IRelationContext - e1 []IRelationContext + parser antlr.Parser + e IRelationContext + s8 antlr.Token + ops []antlr.Token + _relation IRelationContext + e1 []IRelationContext } func NewEmptyConditionalAndContext() *ConditionalAndContext { @@ -1039,7 +977,7 @@ func NewEmptyConditionalAndContext() *ConditionalAndContext { return p } -func InitEmptyConditionalAndContext(p *ConditionalAndContext) { +func InitEmptyConditionalAndContext(p *ConditionalAndContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_conditionalAnd } @@ -1061,32 +999,24 @@ func (s *ConditionalAndContext) GetParser() antlr.Parser { return s.parser } func (s *ConditionalAndContext) GetS8() antlr.Token { return s.s8 } - func (s *ConditionalAndContext) SetS8(v antlr.Token) { s.s8 = v } - func (s *ConditionalAndContext) GetOps() []antlr.Token { return s.ops } - func (s *ConditionalAndContext) SetOps(v []antlr.Token) { s.ops = v } - func (s *ConditionalAndContext) GetE() IRelationContext { return s.e } func (s *ConditionalAndContext) Get_relation() IRelationContext { return s._relation } - func (s *ConditionalAndContext) SetE(v IRelationContext) { s.e = v } func (s *ConditionalAndContext) Set_relation(v IRelationContext) { s._relation = v } - func (s *ConditionalAndContext) GetE1() []IRelationContext { return s.e1 } - func (s *ConditionalAndContext) SetE1(v []IRelationContext) { s.e1 = v } - func (s *ConditionalAndContext) AllRelation() []IRelationContext { children := s.GetChildren() len := 0 @@ -1109,12 +1039,12 @@ func (s *ConditionalAndContext) AllRelation() []IRelationContext { } func (s *ConditionalAndContext) Relation(i int) IRelationContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IRelationContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -1144,7 +1074,6 @@ func (s *ConditionalAndContext) ToStringTree(ruleNames []string, recog antlr.Rec return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *ConditionalAndContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterConditionalAnd(s) @@ -1167,9 +1096,6 @@ func (s *ConditionalAndContext) Accept(visitor antlr.ParseTreeVisitor) interface } } - - - func (p *CELParser) ConditionalAnd() (localctx IConditionalAndContext) { localctx = NewConditionalAndContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 6, CELParserRULE_conditionalAnd) @@ -1177,35 +1103,34 @@ func (p *CELParser) ConditionalAnd() (localctx IConditionalAndContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(51) + p.SetState(53) var _x = p.relation(0) localctx.(*ConditionalAndContext).e = _x } - p.SetState(56) + p.SetState(58) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for _la == CELParserLOGICAL_AND { { - p.SetState(52) + p.SetState(54) var _m = p.Match(CELParserLOGICAL_AND) localctx.(*ConditionalAndContext).s8 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*ConditionalAndContext).ops = append(localctx.(*ConditionalAndContext).ops, localctx.(*ConditionalAndContext).s8) { - p.SetState(53) + p.SetState(55) var _x = p.relation(0) @@ -1213,17 +1138,14 @@ func (p *CELParser) ConditionalAnd() (localctx IConditionalAndContext) { } localctx.(*ConditionalAndContext).e1 = append(localctx.(*ConditionalAndContext).e1, localctx.(*ConditionalAndContext)._relation) - - p.SetState(58) + p.SetState(60) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _la = p.GetTokenStream().LA(1) } - - errorExit: if p.HasError() { v := p.GetError() @@ -1237,7 +1159,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IRelationContext is an interface to support dynamic dispatch. type IRelationContext interface { antlr.ParserRuleContext @@ -1246,12 +1167,10 @@ type IRelationContext interface { GetParser() antlr.Parser // GetOp returns the op token. - GetOp() antlr.Token - + GetOp() antlr.Token // SetOp sets the op token. - SetOp(antlr.Token) - + SetOp(antlr.Token) // Getter signatures Calc() ICalcContext @@ -1272,7 +1191,7 @@ type IRelationContext interface { type RelationContext struct { antlr.BaseParserRuleContext parser antlr.Parser - op antlr.Token + op antlr.Token } func NewEmptyRelationContext() *RelationContext { @@ -1282,7 +1201,7 @@ func NewEmptyRelationContext() *RelationContext { return p } -func InitEmptyRelationContext(p *RelationContext) { +func InitEmptyRelationContext(p *RelationContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_relation } @@ -1304,15 +1223,13 @@ func (s *RelationContext) GetParser() antlr.Parser { return s.parser } func (s *RelationContext) GetOp() antlr.Token { return s.op } - func (s *RelationContext) SetOp(v antlr.Token) { s.op = v } - func (s *RelationContext) Calc() ICalcContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(ICalcContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -1346,12 +1263,12 @@ func (s *RelationContext) AllRelation() []IRelationContext { } func (s *RelationContext) Relation(i int) IRelationContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IRelationContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -1401,7 +1318,6 @@ func (s *RelationContext) ToStringTree(ruleNames []string, recog antlr.Recognize return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *RelationContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterRelation(s) @@ -1424,10 +1340,6 @@ func (s *RelationContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - - func (p *CELParser) Relation() (localctx IRelationContext) { return p.relation(0) } @@ -1447,12 +1359,12 @@ func (p *CELParser) relation(_p int) (localctx IRelationContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(60) + p.SetState(62) p.calc(0) } p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1)) - p.SetState(67) + p.SetState(69) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1469,14 +1381,14 @@ func (p *CELParser) relation(_p int) (localctx IRelationContext) { _prevctx = localctx localctx = NewRelationContext(p, _parentctx, _parentState) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_relation) - p.SetState(62) + p.SetState(64) if !(p.Precpred(p.GetParserRuleContext(), 1)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 1)", "")) goto errorExit } { - p.SetState(63) + p.SetState(65) var _lt = p.GetTokenStream().LT(1) @@ -1484,7 +1396,7 @@ func (p *CELParser) relation(_p int) (localctx IRelationContext) { _la = p.GetTokenStream().LA(1) - if !(((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 254) != 0)) { + if !((int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&254) != 0) { var _ri = p.GetErrorHandler().RecoverInline(p) localctx.(*RelationContext).op = _ri @@ -1494,26 +1406,23 @@ func (p *CELParser) relation(_p int) (localctx IRelationContext) { } } { - p.SetState(64) + p.SetState(66) p.relation(2) } - } - p.SetState(69) + p.SetState(71) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - - errorExit: +errorExit: if p.HasError() { v := p.GetError() localctx.SetException(v) @@ -1526,7 +1435,6 @@ func (p *CELParser) relation(_p int) (localctx IRelationContext) { goto errorExit // Trick to prevent compiler error if the label is not used } - // ICalcContext is an interface to support dynamic dispatch. type ICalcContext interface { antlr.ParserRuleContext @@ -1535,12 +1443,10 @@ type ICalcContext interface { GetParser() antlr.Parser // GetOp returns the op token. - GetOp() antlr.Token - + GetOp() antlr.Token // SetOp sets the op token. - SetOp(antlr.Token) - + SetOp(antlr.Token) // Getter signatures Unary() IUnaryContext @@ -1559,7 +1465,7 @@ type ICalcContext interface { type CalcContext struct { antlr.BaseParserRuleContext parser antlr.Parser - op antlr.Token + op antlr.Token } func NewEmptyCalcContext() *CalcContext { @@ -1569,7 +1475,7 @@ func NewEmptyCalcContext() *CalcContext { return p } -func InitEmptyCalcContext(p *CalcContext) { +func InitEmptyCalcContext(p *CalcContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_calc } @@ -1591,15 +1497,13 @@ func (s *CalcContext) GetParser() antlr.Parser { return s.parser } func (s *CalcContext) GetOp() antlr.Token { return s.op } - func (s *CalcContext) SetOp(v antlr.Token) { s.op = v } - func (s *CalcContext) Unary() IUnaryContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IUnaryContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -1633,12 +1537,12 @@ func (s *CalcContext) AllCalc() []ICalcContext { } func (s *CalcContext) Calc(i int) ICalcContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(ICalcContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -1680,7 +1584,6 @@ func (s *CalcContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) s return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *CalcContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterCalc(s) @@ -1703,10 +1606,6 @@ func (s *CalcContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - - func (p *CELParser) Calc() (localctx ICalcContext) { return p.calc(0) } @@ -1726,12 +1625,12 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(71) + p.SetState(73) p.Unary() } p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1)) - p.SetState(81) + p.SetState(83) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1746,7 +1645,7 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { p.TriggerExitRuleEvent() } _prevctx = localctx - p.SetState(79) + p.SetState(81) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -1756,14 +1655,14 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { case 1: localctx = NewCalcContext(p, _parentctx, _parentState) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_calc) - p.SetState(73) + p.SetState(75) if !(p.Precpred(p.GetParserRuleContext(), 2)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 2)", "")) goto errorExit } { - p.SetState(74) + p.SetState(76) var _lt = p.GetTokenStream().LT(1) @@ -1771,7 +1670,7 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { _la = p.GetTokenStream().LA(1) - if !(((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 58720256) != 0)) { + if !((int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&58720256) != 0) { var _ri = p.GetErrorHandler().RecoverInline(p) localctx.(*CalcContext).op = _ri @@ -1781,22 +1680,21 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { } } { - p.SetState(75) + p.SetState(77) p.calc(3) } - case 2: localctx = NewCalcContext(p, _parentctx, _parentState) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_calc) - p.SetState(76) + p.SetState(78) if !(p.Precpred(p.GetParserRuleContext(), 1)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 1)", "")) goto errorExit } { - p.SetState(77) + p.SetState(79) var _lt = p.GetTokenStream().LT(1) @@ -1814,7 +1712,7 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { } } { - p.SetState(78) + p.SetState(80) p.calc(2) } @@ -1823,20 +1721,18 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { } } - p.SetState(83) + p.SetState(85) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - - errorExit: +errorExit: if p.HasError() { v := p.GetError() localctx.SetException(v) @@ -1849,7 +1745,6 @@ func (p *CELParser) calc(_p int) (localctx ICalcContext) { goto errorExit // Trick to prevent compiler error if the label is not used } - // IUnaryContext is an interface to support dynamic dispatch. type IUnaryContext interface { antlr.ParserRuleContext @@ -1872,7 +1767,7 @@ func NewEmptyUnaryContext() *UnaryContext { return p } -func InitEmptyUnaryContext(p *UnaryContext) { +func InitEmptyUnaryContext(p *UnaryContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_unary } @@ -1904,9 +1799,6 @@ func (s *UnaryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) return antlr.TreesStringTree(s, ruleNames, recog) } - - - type LogicalNotContext struct { UnaryContext s19 antlr.Token @@ -1923,16 +1815,12 @@ func NewLogicalNotContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *Log return p } - func (s *LogicalNotContext) GetS19() antlr.Token { return s.s19 } - func (s *LogicalNotContext) SetS19(v antlr.Token) { s.s19 = v } - func (s *LogicalNotContext) GetOps() []antlr.Token { return s.ops } - func (s *LogicalNotContext) SetOps(v []antlr.Token) { s.ops = v } func (s *LogicalNotContext) GetRuleContext() antlr.RuleContext { @@ -1940,10 +1828,10 @@ func (s *LogicalNotContext) GetRuleContext() antlr.RuleContext { } func (s *LogicalNotContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -1963,7 +1851,6 @@ func (s *LogicalNotContext) EXCLAM(i int) antlr.TerminalNode { return s.GetToken(CELParserEXCLAM, i) } - func (s *LogicalNotContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterLogicalNot(s) @@ -1986,7 +1873,6 @@ func (s *LogicalNotContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type MemberExprContext struct { UnaryContext } @@ -2006,10 +1892,10 @@ func (s *MemberExprContext) GetRuleContext() antlr.RuleContext { } func (s *MemberExprContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2021,7 +1907,6 @@ func (s *MemberExprContext) Member() IMemberContext { return t.(IMemberContext) } - func (s *MemberExprContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterMemberExpr(s) @@ -2044,7 +1929,6 @@ func (s *MemberExprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type NegateContext struct { UnaryContext s18 antlr.Token @@ -2061,16 +1945,12 @@ func NewNegateContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NegateC return p } - func (s *NegateContext) GetS18() antlr.Token { return s.s18 } - func (s *NegateContext) SetS18(v antlr.Token) { s.s18 = v } - func (s *NegateContext) GetOps() []antlr.Token { return s.ops } - func (s *NegateContext) SetOps(v []antlr.Token) { s.ops = v } func (s *NegateContext) GetRuleContext() antlr.RuleContext { @@ -2078,10 +1958,10 @@ func (s *NegateContext) GetRuleContext() antlr.RuleContext { } func (s *NegateContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2101,7 +1981,6 @@ func (s *NegateContext) MINUS(i int) antlr.TerminalNode { return s.GetToken(CELParserMINUS, i) } - func (s *NegateContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterNegate(s) @@ -2124,8 +2003,6 @@ func (s *NegateContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - func (p *CELParser) Unary() (localctx IUnaryContext) { localctx = NewUnaryContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 12, CELParserRULE_unary) @@ -2133,7 +2010,7 @@ func (p *CELParser) Unary() (localctx IUnaryContext) { var _alt int - p.SetState(97) + p.SetState(99) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -2144,54 +2021,50 @@ func (p *CELParser) Unary() (localctx IUnaryContext) { localctx = NewMemberExprContext(p, localctx) p.EnterOuterAlt(localctx, 1) { - p.SetState(84) + p.SetState(86) p.member(0) } - case 2: localctx = NewLogicalNotContext(p, localctx) p.EnterOuterAlt(localctx, 2) - p.SetState(86) + p.SetState(88) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for ok := true; ok; ok = _la == CELParserEXCLAM { { - p.SetState(85) + p.SetState(87) var _m = p.Match(CELParserEXCLAM) localctx.(*LogicalNotContext).s19 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*LogicalNotContext).ops = append(localctx.(*LogicalNotContext).ops, localctx.(*LogicalNotContext).s19) - - p.SetState(88) + p.SetState(90) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _la = p.GetTokenStream().LA(1) } { - p.SetState(90) + p.SetState(92) p.member(0) } - case 3: localctx = NewNegateContext(p, localctx) p.EnterOuterAlt(localctx, 3) - p.SetState(92) + p.SetState(94) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -2200,28 +2073,25 @@ func (p *CELParser) Unary() (localctx IUnaryContext) { for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { switch _alt { case 1: - { - p.SetState(91) + { + p.SetState(93) - var _m = p.Match(CELParserMINUS) + var _m = p.Match(CELParserMINUS) - localctx.(*NegateContext).s18 = _m - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + localctx.(*NegateContext).s18 = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit } - localctx.(*NegateContext).ops = append(localctx.(*NegateContext).ops, localctx.(*NegateContext).s18) - - - + } + localctx.(*NegateContext).ops = append(localctx.(*NegateContext).ops, localctx.(*NegateContext).s18) default: p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) goto errorExit } - p.SetState(94) + p.SetState(96) p.GetErrorHandler().Sync(p) _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) if p.HasError() { @@ -2229,7 +2099,7 @@ func (p *CELParser) Unary() (localctx IUnaryContext) { } } { - p.SetState(96) + p.SetState(98) p.member(0) } @@ -2237,7 +2107,6 @@ func (p *CELParser) Unary() (localctx IUnaryContext) { goto errorExit } - errorExit: if p.HasError() { v := p.GetError() @@ -2251,7 +2120,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IMemberContext is an interface to support dynamic dispatch. type IMemberContext interface { antlr.ParserRuleContext @@ -2274,7 +2142,7 @@ func NewEmptyMemberContext() *MemberContext { return p } -func InitEmptyMemberContext(p *MemberContext) { +func InitEmptyMemberContext(p *MemberContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_member } @@ -2306,16 +2174,12 @@ func (s *MemberContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) return antlr.TreesStringTree(s, ruleNames, recog) } - - - - type MemberCallContext struct { MemberContext - op antlr.Token - id antlr.Token + op antlr.Token + id antlr.Token open antlr.Token - args IExprListContext + args IExprListContext } func NewMemberCallContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *MemberCallContext { @@ -2328,24 +2192,20 @@ func NewMemberCallContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *Mem return p } - func (s *MemberCallContext) GetOp() antlr.Token { return s.op } func (s *MemberCallContext) GetId() antlr.Token { return s.id } func (s *MemberCallContext) GetOpen() antlr.Token { return s.open } - func (s *MemberCallContext) SetOp(v antlr.Token) { s.op = v } func (s *MemberCallContext) SetId(v antlr.Token) { s.id = v } func (s *MemberCallContext) SetOpen(v antlr.Token) { s.open = v } - func (s *MemberCallContext) GetArgs() IExprListContext { return s.args } - func (s *MemberCallContext) SetArgs(v IExprListContext) { s.args = v } func (s *MemberCallContext) GetRuleContext() antlr.RuleContext { @@ -2353,10 +2213,10 @@ func (s *MemberCallContext) GetRuleContext() antlr.RuleContext { } func (s *MemberCallContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2385,10 +2245,10 @@ func (s *MemberCallContext) LPAREN() antlr.TerminalNode { } func (s *MemberCallContext) ExprList() IExprListContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprListContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2400,7 +2260,6 @@ func (s *MemberCallContext) ExprList() IExprListContext { return t.(IExprListContext) } - func (s *MemberCallContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterMemberCall(s) @@ -2423,12 +2282,11 @@ func (s *MemberCallContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type SelectContext struct { MemberContext - op antlr.Token + op antlr.Token opt antlr.Token - id antlr.Token + id IEscapeIdentContext } func NewSelectContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *SelectContext { @@ -2441,29 +2299,27 @@ func NewSelectContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *SelectC return p } - func (s *SelectContext) GetOp() antlr.Token { return s.op } func (s *SelectContext) GetOpt() antlr.Token { return s.opt } -func (s *SelectContext) GetId() antlr.Token { return s.id } - - func (s *SelectContext) SetOp(v antlr.Token) { s.op = v } func (s *SelectContext) SetOpt(v antlr.Token) { s.opt = v } -func (s *SelectContext) SetId(v antlr.Token) { s.id = v } +func (s *SelectContext) GetId() IEscapeIdentContext { return s.id } + +func (s *SelectContext) SetId(v IEscapeIdentContext) { s.id = v } func (s *SelectContext) GetRuleContext() antlr.RuleContext { return s } func (s *SelectContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2479,15 +2335,26 @@ func (s *SelectContext) DOT() antlr.TerminalNode { return s.GetToken(CELParserDOT, 0) } -func (s *SelectContext) IDENTIFIER() antlr.TerminalNode { - return s.GetToken(CELParserIDENTIFIER, 0) +func (s *SelectContext) EscapeIdent() IEscapeIdentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEscapeIdentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IEscapeIdentContext) } func (s *SelectContext) QUESTIONMARK() antlr.TerminalNode { return s.GetToken(CELParserQUESTIONMARK, 0) } - func (s *SelectContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterSelect(s) @@ -2510,7 +2377,6 @@ func (s *SelectContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type PrimaryExprContext struct { MemberContext } @@ -2530,10 +2396,10 @@ func (s *PrimaryExprContext) GetRuleContext() antlr.RuleContext { } func (s *PrimaryExprContext) Primary() IPrimaryContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IPrimaryContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2545,7 +2411,6 @@ func (s *PrimaryExprContext) Primary() IPrimaryContext { return t.(IPrimaryContext) } - func (s *PrimaryExprContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterPrimaryExpr(s) @@ -2568,12 +2433,11 @@ func (s *PrimaryExprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} } } - type IndexContext struct { MemberContext - op antlr.Token - opt antlr.Token - index IExprContext + op antlr.Token + opt antlr.Token + index IExprContext } func NewIndexContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IndexContext { @@ -2586,20 +2450,16 @@ func NewIndexContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IndexCon return p } - func (s *IndexContext) GetOp() antlr.Token { return s.op } func (s *IndexContext) GetOpt() antlr.Token { return s.opt } - func (s *IndexContext) SetOp(v antlr.Token) { s.op = v } func (s *IndexContext) SetOpt(v antlr.Token) { s.opt = v } - func (s *IndexContext) GetIndex() IExprContext { return s.index } - func (s *IndexContext) SetIndex(v IExprContext) { s.index = v } func (s *IndexContext) GetRuleContext() antlr.RuleContext { @@ -2607,10 +2467,10 @@ func (s *IndexContext) GetRuleContext() antlr.RuleContext { } func (s *IndexContext) Member() IMemberContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMemberContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2631,10 +2491,10 @@ func (s *IndexContext) LBRACKET() antlr.TerminalNode { } func (s *IndexContext) Expr() IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -2650,7 +2510,6 @@ func (s *IndexContext) QUESTIONMARK() antlr.TerminalNode { return s.GetToken(CELParserQUESTIONMARK, 0) } - func (s *IndexContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterIndex(s) @@ -2673,8 +2532,6 @@ func (s *IndexContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - func (p *CELParser) Member() (localctx IMemberContext) { return p.member(0) } @@ -2698,12 +2555,12 @@ func (p *CELParser) member(_p int) (localctx IMemberContext) { _prevctx = localctx { - p.SetState(100) + p.SetState(102) p.Primary() } p.GetParserRuleContext().SetStop(p.GetTokenStream().LT(-1)) - p.SetState(126) + p.SetState(128) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -2718,7 +2575,7 @@ func (p *CELParser) member(_p int) (localctx IMemberContext) { p.TriggerExitRuleEvent() } _prevctx = localctx - p.SetState(124) + p.SetState(126) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -2728,185 +2585,174 @@ func (p *CELParser) member(_p int) (localctx IMemberContext) { case 1: localctx = NewSelectContext(p, NewMemberContext(p, _parentctx, _parentState)) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_member) - p.SetState(102) + p.SetState(104) if !(p.Precpred(p.GetParserRuleContext(), 3)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 3)", "")) goto errorExit } { - p.SetState(103) + p.SetState(105) var _m = p.Match(CELParserDOT) localctx.(*SelectContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(105) + p.SetState(107) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserQUESTIONMARK { { - p.SetState(104) + p.SetState(106) var _m = p.Match(CELParserQUESTIONMARK) localctx.(*SelectContext).opt = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(107) + p.SetState(109) - var _m = p.Match(CELParserIDENTIFIER) + var _x = p.EscapeIdent() - localctx.(*SelectContext).id = _m - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + localctx.(*SelectContext).id = _x } - case 2: localctx = NewMemberCallContext(p, NewMemberContext(p, _parentctx, _parentState)) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_member) - p.SetState(108) + p.SetState(110) if !(p.Precpred(p.GetParserRuleContext(), 2)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 2)", "")) goto errorExit } { - p.SetState(109) + p.SetState(111) var _m = p.Match(CELParserDOT) localctx.(*MemberCallContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(110) + p.SetState(112) var _m = p.Match(CELParserIDENTIFIER) localctx.(*MemberCallContext).id = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(111) + p.SetState(113) var _m = p.Match(CELParserLPAREN) localctx.(*MemberCallContext).open = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(113) + p.SetState(115) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - - if ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 135762105344) != 0) { + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&135762105344) != 0 { { - p.SetState(112) + p.SetState(114) var _x = p.ExprList() - localctx.(*MemberCallContext).args = _x } } { - p.SetState(115) + p.SetState(117) p.Match(CELParserRPAREN) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 3: localctx = NewIndexContext(p, NewMemberContext(p, _parentctx, _parentState)) p.PushNewRecursionContext(localctx, _startState, CELParserRULE_member) - p.SetState(116) + p.SetState(118) if !(p.Precpred(p.GetParserRuleContext(), 1)) { p.SetError(antlr.NewFailedPredicateException(p, "p.Precpred(p.GetParserRuleContext(), 1)", "")) goto errorExit } { - p.SetState(117) + p.SetState(119) var _m = p.Match(CELParserLBRACKET) localctx.(*IndexContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(119) + p.SetState(121) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserQUESTIONMARK { { - p.SetState(118) + p.SetState(120) var _m = p.Match(CELParserQUESTIONMARK) localctx.(*IndexContext).opt = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(121) + p.SetState(123) var _x = p.Expr() - localctx.(*IndexContext).index = _x } { - p.SetState(122) + p.SetState(124) p.Match(CELParserRPRACKET) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } @@ -2915,20 +2761,18 @@ func (p *CELParser) member(_p int) (localctx IMemberContext) { } } - p.SetState(128) + p.SetState(130) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 13, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - - errorExit: +errorExit: if p.HasError() { v := p.GetError() localctx.SetException(v) @@ -2941,7 +2785,6 @@ func (p *CELParser) member(_p int) (localctx IMemberContext) { goto errorExit // Trick to prevent compiler error if the label is not used } - // IPrimaryContext is an interface to support dynamic dispatch. type IPrimaryContext interface { antlr.ParserRuleContext @@ -2964,7 +2807,7 @@ func NewEmptyPrimaryContext() *PrimaryContext { return p } -func InitEmptyPrimaryContext(p *PrimaryContext) { +func InitEmptyPrimaryContext(p *PrimaryContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_primary } @@ -2996,13 +2839,10 @@ func (s *PrimaryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer return antlr.TreesStringTree(s, ruleNames, recog) } - - - type CreateListContext struct { PrimaryContext - op antlr.Token - elems IListInitContext + op antlr.Token + elems IListInitContext } func NewCreateListContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *CreateListContext { @@ -3015,16 +2855,12 @@ func NewCreateListContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *Cre return p } - func (s *CreateListContext) GetOp() antlr.Token { return s.op } - func (s *CreateListContext) SetOp(v antlr.Token) { s.op = v } - func (s *CreateListContext) GetElems() IListInitContext { return s.elems } - func (s *CreateListContext) SetElems(v IListInitContext) { s.elems = v } func (s *CreateListContext) GetRuleContext() antlr.RuleContext { @@ -3044,10 +2880,10 @@ func (s *CreateListContext) COMMA() antlr.TerminalNode { } func (s *CreateListContext) ListInit() IListInitContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IListInitContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3059,7 +2895,6 @@ func (s *CreateListContext) ListInit() IListInitContext { return t.(IListInitContext) } - func (s *CreateListContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterCreateList(s) @@ -3082,11 +2917,68 @@ func (s *CreateListContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } +type IdentContext struct { + PrimaryContext + leadingDot antlr.Token + id antlr.Token +} + +func NewIdentContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IdentContext { + var p = new(IdentContext) + + InitEmptyPrimaryContext(&p.PrimaryContext) + p.parser = parser + p.CopyAll(ctx.(*PrimaryContext)) + + return p +} + +func (s *IdentContext) GetLeadingDot() antlr.Token { return s.leadingDot } + +func (s *IdentContext) GetId() antlr.Token { return s.id } + +func (s *IdentContext) SetLeadingDot(v antlr.Token) { s.leadingDot = v } + +func (s *IdentContext) SetId(v antlr.Token) { s.id = v } + +func (s *IdentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *IdentContext) IDENTIFIER() antlr.TerminalNode { + return s.GetToken(CELParserIDENTIFIER, 0) +} + +func (s *IdentContext) DOT() antlr.TerminalNode { + return s.GetToken(CELParserDOT, 0) +} + +func (s *IdentContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.EnterIdent(s) + } +} + +func (s *IdentContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.ExitIdent(s) + } +} + +func (s *IdentContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { + switch t := visitor.(type) { + case CELVisitor: + return t.VisitIdent(s) + + default: + return t.VisitChildren(s) + } +} type CreateStructContext struct { PrimaryContext - op antlr.Token - entries IMapInitializerListContext + op antlr.Token + entries IMapInitializerListContext } func NewCreateStructContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *CreateStructContext { @@ -3099,16 +2991,12 @@ func NewCreateStructContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *C return p } - func (s *CreateStructContext) GetOp() antlr.Token { return s.op } - func (s *CreateStructContext) SetOp(v antlr.Token) { s.op = v } - func (s *CreateStructContext) GetEntries() IMapInitializerListContext { return s.entries } - func (s *CreateStructContext) SetEntries(v IMapInitializerListContext) { s.entries = v } func (s *CreateStructContext) GetRuleContext() antlr.RuleContext { @@ -3128,10 +3016,10 @@ func (s *CreateStructContext) COMMA() antlr.TerminalNode { } func (s *CreateStructContext) MapInitializerList() IMapInitializerListContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IMapInitializerListContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3143,7 +3031,6 @@ func (s *CreateStructContext) MapInitializerList() IMapInitializerListContext { return t.(IMapInitializerListContext) } - func (s *CreateStructContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterCreateStruct(s) @@ -3166,7 +3053,6 @@ func (s *CreateStructContext) Accept(visitor antlr.ParseTreeVisitor) interface{} } } - type ConstantLiteralContext struct { PrimaryContext } @@ -3186,10 +3072,10 @@ func (s *ConstantLiteralContext) GetRuleContext() antlr.RuleContext { } func (s *ConstantLiteralContext) Literal() ILiteralContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(ILiteralContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3201,7 +3087,6 @@ func (s *ConstantLiteralContext) Literal() ILiteralContext { return t.(ILiteralContext) } - func (s *ConstantLiteralContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterConstantLiteral(s) @@ -3224,10 +3109,9 @@ func (s *ConstantLiteralContext) Accept(visitor antlr.ParseTreeVisitor) interfac } } - type NestedContext struct { PrimaryContext - e IExprContext + e IExprContext } func NewNestedContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NestedContext { @@ -3240,10 +3124,8 @@ func NewNestedContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NestedC return p } - func (s *NestedContext) GetE() IExprContext { return s.e } - func (s *NestedContext) SetE(v IExprContext) { s.e = v } func (s *NestedContext) GetRuleContext() antlr.RuleContext { @@ -3259,10 +3141,10 @@ func (s *NestedContext) RPAREN() antlr.TerminalNode { } func (s *NestedContext) Expr() IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3274,7 +3156,6 @@ func (s *NestedContext) Expr() IExprContext { return t.(IExprContext) } - func (s *NestedContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterNested(s) @@ -3297,16 +3178,15 @@ func (s *NestedContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type CreateMessageContext struct { PrimaryContext - leadingDot antlr.Token + leadingDot antlr.Token _IDENTIFIER antlr.Token - ids []antlr.Token - s16 antlr.Token - ops []antlr.Token - op antlr.Token - entries IFieldInitializerListContext + ids []antlr.Token + s16 antlr.Token + ops []antlr.Token + op antlr.Token + entries IFieldInitializerListContext } func NewCreateMessageContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *CreateMessageContext { @@ -3319,7 +3199,6 @@ func NewCreateMessageContext(parser antlr.Parser, ctx antlr.ParserRuleContext) * return p } - func (s *CreateMessageContext) GetLeadingDot() antlr.Token { return s.leadingDot } func (s *CreateMessageContext) Get_IDENTIFIER() antlr.Token { return s._IDENTIFIER } @@ -3328,7 +3207,6 @@ func (s *CreateMessageContext) GetS16() antlr.Token { return s.s16 } func (s *CreateMessageContext) GetOp() antlr.Token { return s.op } - func (s *CreateMessageContext) SetLeadingDot(v antlr.Token) { s.leadingDot = v } func (s *CreateMessageContext) Set_IDENTIFIER(v antlr.Token) { s._IDENTIFIER = v } @@ -3337,20 +3215,16 @@ func (s *CreateMessageContext) SetS16(v antlr.Token) { s.s16 = v } func (s *CreateMessageContext) SetOp(v antlr.Token) { s.op = v } - func (s *CreateMessageContext) GetIds() []antlr.Token { return s.ids } func (s *CreateMessageContext) GetOps() []antlr.Token { return s.ops } - func (s *CreateMessageContext) SetIds(v []antlr.Token) { s.ids = v } func (s *CreateMessageContext) SetOps(v []antlr.Token) { s.ops = v } - func (s *CreateMessageContext) GetEntries() IFieldInitializerListContext { return s.entries } - func (s *CreateMessageContext) SetEntries(v IFieldInitializerListContext) { s.entries = v } func (s *CreateMessageContext) GetRuleContext() antlr.RuleContext { @@ -3386,10 +3260,10 @@ func (s *CreateMessageContext) DOT(i int) antlr.TerminalNode { } func (s *CreateMessageContext) FieldInitializerList() IFieldInitializerListContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IFieldInitializerListContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3401,7 +3275,6 @@ func (s *CreateMessageContext) FieldInitializerList() IFieldInitializerListConte return t.(IFieldInitializerListContext) } - func (s *CreateMessageContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterCreateMessage(s) @@ -3424,17 +3297,16 @@ func (s *CreateMessageContext) Accept(visitor antlr.ParseTreeVisitor) interface{ } } - -type IdentOrGlobalCallContext struct { +type GlobalCallContext struct { PrimaryContext leadingDot antlr.Token - id antlr.Token - op antlr.Token - args IExprListContext + id antlr.Token + op antlr.Token + args IExprListContext } -func NewIdentOrGlobalCallContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IdentOrGlobalCallContext { - var p = new(IdentOrGlobalCallContext) +func NewGlobalCallContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *GlobalCallContext { + var p = new(GlobalCallContext) InitEmptyPrimaryContext(&p.PrimaryContext) p.parser = parser @@ -3443,51 +3315,47 @@ func NewIdentOrGlobalCallContext(parser antlr.Parser, ctx antlr.ParserRuleContex return p } +func (s *GlobalCallContext) GetLeadingDot() antlr.Token { return s.leadingDot } -func (s *IdentOrGlobalCallContext) GetLeadingDot() antlr.Token { return s.leadingDot } +func (s *GlobalCallContext) GetId() antlr.Token { return s.id } -func (s *IdentOrGlobalCallContext) GetId() antlr.Token { return s.id } +func (s *GlobalCallContext) GetOp() antlr.Token { return s.op } -func (s *IdentOrGlobalCallContext) GetOp() antlr.Token { return s.op } +func (s *GlobalCallContext) SetLeadingDot(v antlr.Token) { s.leadingDot = v } +func (s *GlobalCallContext) SetId(v antlr.Token) { s.id = v } -func (s *IdentOrGlobalCallContext) SetLeadingDot(v antlr.Token) { s.leadingDot = v } +func (s *GlobalCallContext) SetOp(v antlr.Token) { s.op = v } -func (s *IdentOrGlobalCallContext) SetId(v antlr.Token) { s.id = v } +func (s *GlobalCallContext) GetArgs() IExprListContext { return s.args } -func (s *IdentOrGlobalCallContext) SetOp(v antlr.Token) { s.op = v } +func (s *GlobalCallContext) SetArgs(v IExprListContext) { s.args = v } - -func (s *IdentOrGlobalCallContext) GetArgs() IExprListContext { return s.args } - - -func (s *IdentOrGlobalCallContext) SetArgs(v IExprListContext) { s.args = v } - -func (s *IdentOrGlobalCallContext) GetRuleContext() antlr.RuleContext { +func (s *GlobalCallContext) GetRuleContext() antlr.RuleContext { return s } -func (s *IdentOrGlobalCallContext) IDENTIFIER() antlr.TerminalNode { +func (s *GlobalCallContext) IDENTIFIER() antlr.TerminalNode { return s.GetToken(CELParserIDENTIFIER, 0) } -func (s *IdentOrGlobalCallContext) RPAREN() antlr.TerminalNode { +func (s *GlobalCallContext) RPAREN() antlr.TerminalNode { return s.GetToken(CELParserRPAREN, 0) } -func (s *IdentOrGlobalCallContext) DOT() antlr.TerminalNode { - return s.GetToken(CELParserDOT, 0) -} - -func (s *IdentOrGlobalCallContext) LPAREN() antlr.TerminalNode { +func (s *GlobalCallContext) LPAREN() antlr.TerminalNode { return s.GetToken(CELParserLPAREN, 0) } -func (s *IdentOrGlobalCallContext) ExprList() IExprListContext { - var t antlr.RuleContext; +func (s *GlobalCallContext) DOT() antlr.TerminalNode { + return s.GetToken(CELParserDOT, 0) +} + +func (s *GlobalCallContext) ExprList() IExprListContext { + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprListContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -3499,37 +3367,34 @@ func (s *IdentOrGlobalCallContext) ExprList() IExprListContext { return t.(IExprListContext) } - -func (s *IdentOrGlobalCallContext) EnterRule(listener antlr.ParseTreeListener) { +func (s *GlobalCallContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { - listenerT.EnterIdentOrGlobalCall(s) + listenerT.EnterGlobalCall(s) } } -func (s *IdentOrGlobalCallContext) ExitRule(listener antlr.ParseTreeListener) { +func (s *GlobalCallContext) ExitRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { - listenerT.ExitIdentOrGlobalCall(s) + listenerT.ExitGlobalCall(s) } } -func (s *IdentOrGlobalCallContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { +func (s *GlobalCallContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { switch t := visitor.(type) { case CELVisitor: - return t.VisitIdentOrGlobalCall(s) + return t.VisitGlobalCall(s) default: return t.VisitChildren(s) } } - - func (p *CELParser) Primary() (localctx IPrimaryContext) { localctx = NewPrimaryContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 16, CELParserRULE_primary) var _la int - p.SetState(180) + p.SetState(184) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -3537,246 +3402,230 @@ func (p *CELParser) Primary() (localctx IPrimaryContext) { switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 25, p.GetParserRuleContext()) { case 1: - localctx = NewIdentOrGlobalCallContext(p, localctx) + localctx = NewIdentContext(p, localctx) p.EnterOuterAlt(localctx, 1) - p.SetState(130) + p.SetState(132) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserDOT { { - p.SetState(129) + p.SetState(131) var _m = p.Match(CELParserDOT) - localctx.(*IdentOrGlobalCallContext).leadingDot = _m + localctx.(*IdentContext).leadingDot = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(132) + p.SetState(134) var _m = p.Match(CELParserIDENTIFIER) - localctx.(*IdentOrGlobalCallContext).id = _m - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(138) - p.GetErrorHandler().Sync(p) - - - if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 16, p.GetParserRuleContext()) == 1 { - { - p.SetState(133) - - var _m = p.Match(CELParserLPAREN) - - localctx.(*IdentOrGlobalCallContext).op = _m - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - p.SetState(135) - p.GetErrorHandler().Sync(p) + localctx.(*IdentContext).id = _m if p.HasError() { + // Recognition error - abort rule goto errorExit } - _la = p.GetTokenStream().LA(1) - - - if ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 135762105344) != 0) { - { - p.SetState(134) - - var _x = p.ExprList() - - - localctx.(*IdentOrGlobalCallContext).args = _x - } - - } - { - p.SetState(137) - p.Match(CELParserRPAREN) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } else if p.HasError() { // JIM - goto errorExit } - case 2: - localctx = NewNestedContext(p, localctx) + localctx = NewGlobalCallContext(p, localctx) p.EnterOuterAlt(localctx, 2) - { - p.SetState(140) - p.Match(CELParserLPAREN) - if p.HasError() { + p.SetState(136) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == CELParserDOT { + { + p.SetState(135) + + var _m = p.Match(CELParserDOT) + + localctx.(*GlobalCallContext).leadingDot = _m + if p.HasError() { // Recognition error - abort rule goto errorExit + } + } + + } + { + p.SetState(138) + + var _m = p.Match(CELParserIDENTIFIER) + + localctx.(*GlobalCallContext).id = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + { + p.SetState(139) + + var _m = p.Match(CELParserLPAREN) + + localctx.(*GlobalCallContext).op = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(141) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&135762105344) != 0 { + { + p.SetState(140) + + var _x = p.ExprList() + + localctx.(*GlobalCallContext).args = _x + } + + } + { + p.SetState(143) + p.Match(CELParserRPAREN) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + case 3: + localctx = NewNestedContext(p, localctx) + p.EnterOuterAlt(localctx, 3) + { + p.SetState(144) + p.Match(CELParserLPAREN) + if p.HasError() { + // Recognition error - abort rule + goto errorExit } } { - p.SetState(141) + p.SetState(145) var _x = p.Expr() - localctx.(*NestedContext).e = _x } { - p.SetState(142) + p.SetState(146) p.Match(CELParserRPAREN) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - - case 3: + case 4: localctx = NewCreateListContext(p, localctx) - p.EnterOuterAlt(localctx, 3) + p.EnterOuterAlt(localctx, 4) { - p.SetState(144) + p.SetState(148) var _m = p.Match(CELParserLBRACKET) localctx.(*CreateListContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(146) + p.SetState(150) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - - if ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 135763153920) != 0) { + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&135763153920) != 0 { { - p.SetState(145) + p.SetState(149) var _x = p.ListInit() - localctx.(*CreateListContext).elems = _x } } - p.SetState(149) + p.SetState(153) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserCOMMA { { - p.SetState(148) + p.SetState(152) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(151) + p.SetState(155) p.Match(CELParserRPRACKET) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - - case 4: + case 5: localctx = NewCreateStructContext(p, localctx) - p.EnterOuterAlt(localctx, 4) + p.EnterOuterAlt(localctx, 5) { - p.SetState(152) + p.SetState(156) var _m = p.Match(CELParserLBRACE) localctx.(*CreateStructContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(154) + p.SetState(158) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - - if ((int64(_la) & ^0x3f) == 0 && ((int64(1) << _la) & 135763153920) != 0) { + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&135763153920) != 0 { { - p.SetState(153) + p.SetState(157) var _x = p.MapInitializerList() - localctx.(*CreateStructContext).entries = _x } } - p.SetState(157) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - - if _la == CELParserCOMMA { - { - p.SetState(156) - p.Match(CELParserCOMMA) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - } - { - p.SetState(159) - p.Match(CELParserRBRACE) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } - } - - - case 5: - localctx = NewCreateMessageContext(p, localctx) - p.EnterOuterAlt(localctx, 5) p.SetState(161) p.GetErrorHandler().Sync(p) if p.HasError() { @@ -3784,139 +3633,162 @@ func (p *CELParser) Primary() (localctx IPrimaryContext) { } _la = p.GetTokenStream().LA(1) - - if _la == CELParserDOT { + if _la == CELParserCOMMA { { p.SetState(160) - - var _m = p.Match(CELParserDOT) - - localctx.(*CreateMessageContext).leadingDot = _m + p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { p.SetState(163) - - var _m = p.Match(CELParserIDENTIFIER) - - localctx.(*CreateMessageContext)._IDENTIFIER = _m + p.Match(CELParserRBRACE) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - localctx.(*CreateMessageContext).ids = append(localctx.(*CreateMessageContext).ids, localctx.(*CreateMessageContext)._IDENTIFIER) - p.SetState(168) + + case 6: + localctx = NewCreateMessageContext(p, localctx) + p.EnterOuterAlt(localctx, 6) + p.SetState(165) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - - for _la == CELParserDOT { + if _la == CELParserDOT { { p.SetState(164) var _m = p.Match(CELParserDOT) + localctx.(*CreateMessageContext).leadingDot = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + { + p.SetState(167) + + var _m = p.Match(CELParserIDENTIFIER) + + localctx.(*CreateMessageContext)._IDENTIFIER = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + localctx.(*CreateMessageContext).ids = append(localctx.(*CreateMessageContext).ids, localctx.(*CreateMessageContext)._IDENTIFIER) + p.SetState(172) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == CELParserDOT { + { + p.SetState(168) + + var _m = p.Match(CELParserDOT) + localctx.(*CreateMessageContext).s16 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*CreateMessageContext).ops = append(localctx.(*CreateMessageContext).ops, localctx.(*CreateMessageContext).s16) { - p.SetState(165) + p.SetState(169) var _m = p.Match(CELParserIDENTIFIER) localctx.(*CreateMessageContext)._IDENTIFIER = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*CreateMessageContext).ids = append(localctx.(*CreateMessageContext).ids, localctx.(*CreateMessageContext)._IDENTIFIER) - - p.SetState(170) + p.SetState(174) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _la = p.GetTokenStream().LA(1) } { - p.SetState(171) + p.SetState(175) var _m = p.Match(CELParserLBRACE) localctx.(*CreateMessageContext).op = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - p.SetState(173) + p.SetState(177) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - - if _la == CELParserQUESTIONMARK || _la == CELParserIDENTIFIER { + if (int64(_la) & ^0x3f) == 0 && ((int64(1)<<_la)&206159478784) != 0 { { - p.SetState(172) + p.SetState(176) var _x = p.FieldInitializerList() - localctx.(*CreateMessageContext).entries = _x } } - p.SetState(176) + p.SetState(180) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserCOMMA { { - p.SetState(175) + p.SetState(179) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(178) + p.SetState(182) p.Match(CELParserRBRACE) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - - case 6: + case 7: localctx = NewConstantLiteralContext(p, localctx) - p.EnterOuterAlt(localctx, 6) + p.EnterOuterAlt(localctx, 7) { - p.SetState(179) + p.SetState(183) p.Literal() } @@ -3924,7 +3796,6 @@ func (p *CELParser) Primary() (localctx IPrimaryContext) { goto errorExit } - errorExit: if p.HasError() { v := p.GetError() @@ -3938,7 +3809,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IExprListContext is an interface to support dynamic dispatch. type IExprListContext interface { antlr.ParserRuleContext @@ -3949,18 +3819,14 @@ type IExprListContext interface { // Get_expr returns the _expr rule contexts. Get_expr() IExprContext - // Set_expr sets the _expr rule contexts. Set_expr(IExprContext) - // GetE returns the e rule context list. GetE() []IExprContext - // SetE sets the e rule context list. - SetE([]IExprContext) - + SetE([]IExprContext) // Getter signatures AllExpr() []IExprContext @@ -3975,8 +3841,8 @@ type IExprListContext interface { type ExprListContext struct { antlr.BaseParserRuleContext parser antlr.Parser - _expr IExprContext - e []IExprContext + _expr IExprContext + e []IExprContext } func NewEmptyExprListContext() *ExprListContext { @@ -3986,7 +3852,7 @@ func NewEmptyExprListContext() *ExprListContext { return p } -func InitEmptyExprListContext(p *ExprListContext) { +func InitEmptyExprListContext(p *ExprListContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_exprList } @@ -4008,16 +3874,12 @@ func (s *ExprListContext) GetParser() antlr.Parser { return s.parser } func (s *ExprListContext) Get_expr() IExprContext { return s._expr } - func (s *ExprListContext) Set_expr(v IExprContext) { s._expr = v } - func (s *ExprListContext) GetE() []IExprContext { return s.e } - func (s *ExprListContext) SetE(v []IExprContext) { s.e = v } - func (s *ExprListContext) AllExpr() []IExprContext { children := s.GetChildren() len := 0 @@ -4040,12 +3902,12 @@ func (s *ExprListContext) AllExpr() []IExprContext { } func (s *ExprListContext) Expr(i int) IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -4075,7 +3937,6 @@ func (s *ExprListContext) ToStringTree(ruleNames []string, recog antlr.Recognize return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *ExprListContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterExprList(s) @@ -4098,9 +3959,6 @@ func (s *ExprListContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) ExprList() (localctx IExprListContext) { localctx = NewExprListContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 18, CELParserRULE_exprList) @@ -4108,52 +3966,46 @@ func (p *CELParser) ExprList() (localctx IExprListContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(182) + p.SetState(186) var _x = p.Expr() - localctx.(*ExprListContext)._expr = _x } localctx.(*ExprListContext).e = append(localctx.(*ExprListContext).e, localctx.(*ExprListContext)._expr) - p.SetState(187) + p.SetState(191) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for _la == CELParserCOMMA { { - p.SetState(183) + p.SetState(187) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(184) + p.SetState(188) var _x = p.Expr() - localctx.(*ExprListContext)._expr = _x } localctx.(*ExprListContext).e = append(localctx.(*ExprListContext).e, localctx.(*ExprListContext)._expr) - - p.SetState(189) + p.SetState(193) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _la = p.GetTokenStream().LA(1) } - - errorExit: if p.HasError() { v := p.GetError() @@ -4167,7 +4019,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IListInitContext is an interface to support dynamic dispatch. type IListInitContext interface { antlr.ParserRuleContext @@ -4178,18 +4029,14 @@ type IListInitContext interface { // Get_optExpr returns the _optExpr rule contexts. Get_optExpr() IOptExprContext - // Set_optExpr sets the _optExpr rule contexts. Set_optExpr(IOptExprContext) - // GetElems returns the elems rule context list. GetElems() []IOptExprContext - // SetElems sets the elems rule context list. - SetElems([]IOptExprContext) - + SetElems([]IOptExprContext) // Getter signatures AllOptExpr() []IOptExprContext @@ -4203,9 +4050,9 @@ type IListInitContext interface { type ListInitContext struct { antlr.BaseParserRuleContext - parser antlr.Parser - _optExpr IOptExprContext - elems []IOptExprContext + parser antlr.Parser + _optExpr IOptExprContext + elems []IOptExprContext } func NewEmptyListInitContext() *ListInitContext { @@ -4215,7 +4062,7 @@ func NewEmptyListInitContext() *ListInitContext { return p } -func InitEmptyListInitContext(p *ListInitContext) { +func InitEmptyListInitContext(p *ListInitContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_listInit } @@ -4237,16 +4084,12 @@ func (s *ListInitContext) GetParser() antlr.Parser { return s.parser } func (s *ListInitContext) Get_optExpr() IOptExprContext { return s._optExpr } - func (s *ListInitContext) Set_optExpr(v IOptExprContext) { s._optExpr = v } - func (s *ListInitContext) GetElems() []IOptExprContext { return s.elems } - func (s *ListInitContext) SetElems(v []IOptExprContext) { s.elems = v } - func (s *ListInitContext) AllOptExpr() []IOptExprContext { children := s.GetChildren() len := 0 @@ -4269,12 +4112,12 @@ func (s *ListInitContext) AllOptExpr() []IOptExprContext { } func (s *ListInitContext) OptExpr(i int) IOptExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IOptExprContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -4304,7 +4147,6 @@ func (s *ListInitContext) ToStringTree(ruleNames []string, recog antlr.Recognize return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *ListInitContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterListInit(s) @@ -4327,9 +4169,6 @@ func (s *ListInitContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) ListInit() (localctx IListInitContext) { localctx = NewListInitContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 20, CELParserRULE_listInit) @@ -4337,15 +4176,14 @@ func (p *CELParser) ListInit() (localctx IListInitContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(190) + p.SetState(194) var _x = p.OptExpr() - localctx.(*ListInitContext)._optExpr = _x } localctx.(*ListInitContext).elems = append(localctx.(*ListInitContext).elems, localctx.(*ListInitContext)._optExpr) - p.SetState(195) + p.SetState(199) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4357,38 +4195,34 @@ func (p *CELParser) ListInit() (localctx IListInitContext) { for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(191) + p.SetState(195) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(192) + p.SetState(196) var _x = p.OptExpr() - localctx.(*ListInitContext)._optExpr = _x } localctx.(*ListInitContext).elems = append(localctx.(*ListInitContext).elems, localctx.(*ListInitContext)._optExpr) - } - p.SetState(197) + p.SetState(201) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 27, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - errorExit: if p.HasError() { v := p.GetError() @@ -4402,7 +4236,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IFieldInitializerListContext is an interface to support dynamic dispatch. type IFieldInitializerListContext interface { antlr.ParserRuleContext @@ -4411,48 +4244,40 @@ type IFieldInitializerListContext interface { GetParser() antlr.Parser // GetS21 returns the s21 token. - GetS21() antlr.Token - + GetS21() antlr.Token // SetS21 sets the s21 token. - SetS21(antlr.Token) - + SetS21(antlr.Token) // GetCols returns the cols token list. GetCols() []antlr.Token - // SetCols sets the cols token list. SetCols([]antlr.Token) - // Get_optField returns the _optField rule contexts. Get_optField() IOptFieldContext // Get_expr returns the _expr rule contexts. Get_expr() IExprContext - // Set_optField sets the _optField rule contexts. Set_optField(IOptFieldContext) // Set_expr sets the _expr rule contexts. Set_expr(IExprContext) - // GetFields returns the fields rule context list. GetFields() []IOptFieldContext // GetValues returns the values rule context list. GetValues() []IExprContext - // SetFields sets the fields rule context list. - SetFields([]IOptFieldContext) + SetFields([]IOptFieldContext) // SetValues sets the values rule context list. - SetValues([]IExprContext) - + SetValues([]IExprContext) // Getter signatures AllOptField() []IOptFieldContext @@ -4470,13 +4295,13 @@ type IFieldInitializerListContext interface { type FieldInitializerListContext struct { antlr.BaseParserRuleContext - parser antlr.Parser - _optField IOptFieldContext - fields []IOptFieldContext - s21 antlr.Token - cols []antlr.Token - _expr IExprContext - values []IExprContext + parser antlr.Parser + _optField IOptFieldContext + fields []IOptFieldContext + s21 antlr.Token + cols []antlr.Token + _expr IExprContext + values []IExprContext } func NewEmptyFieldInitializerListContext() *FieldInitializerListContext { @@ -4486,7 +4311,7 @@ func NewEmptyFieldInitializerListContext() *FieldInitializerListContext { return p } -func InitEmptyFieldInitializerListContext(p *FieldInitializerListContext) { +func InitEmptyFieldInitializerListContext(p *FieldInitializerListContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_fieldInitializerList } @@ -4508,36 +4333,28 @@ func (s *FieldInitializerListContext) GetParser() antlr.Parser { return s.parser func (s *FieldInitializerListContext) GetS21() antlr.Token { return s.s21 } - func (s *FieldInitializerListContext) SetS21(v antlr.Token) { s.s21 = v } - func (s *FieldInitializerListContext) GetCols() []antlr.Token { return s.cols } - func (s *FieldInitializerListContext) SetCols(v []antlr.Token) { s.cols = v } - func (s *FieldInitializerListContext) Get_optField() IOptFieldContext { return s._optField } func (s *FieldInitializerListContext) Get_expr() IExprContext { return s._expr } - func (s *FieldInitializerListContext) Set_optField(v IOptFieldContext) { s._optField = v } func (s *FieldInitializerListContext) Set_expr(v IExprContext) { s._expr = v } - func (s *FieldInitializerListContext) GetFields() []IOptFieldContext { return s.fields } func (s *FieldInitializerListContext) GetValues() []IExprContext { return s.values } - func (s *FieldInitializerListContext) SetFields(v []IOptFieldContext) { s.fields = v } func (s *FieldInitializerListContext) SetValues(v []IExprContext) { s.values = v } - func (s *FieldInitializerListContext) AllOptField() []IOptFieldContext { children := s.GetChildren() len := 0 @@ -4560,12 +4377,12 @@ func (s *FieldInitializerListContext) AllOptField() []IOptFieldContext { } func (s *FieldInitializerListContext) OptField(i int) IOptFieldContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IOptFieldContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -4609,12 +4426,12 @@ func (s *FieldInitializerListContext) AllExpr() []IExprContext { } func (s *FieldInitializerListContext) Expr(i int) IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -4644,7 +4461,6 @@ func (s *FieldInitializerListContext) ToStringTree(ruleNames []string, recog ant return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *FieldInitializerListContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterFieldInitializerList(s) @@ -4667,9 +4483,6 @@ func (s *FieldInitializerListContext) Accept(visitor antlr.ParseTreeVisitor) int } } - - - func (p *CELParser) FieldInitializerList() (localctx IFieldInitializerListContext) { localctx = NewFieldInitializerListContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 22, CELParserRULE_fieldInitializerList) @@ -4677,36 +4490,34 @@ func (p *CELParser) FieldInitializerList() (localctx IFieldInitializerListContex p.EnterOuterAlt(localctx, 1) { - p.SetState(198) + p.SetState(202) var _x = p.OptField() - localctx.(*FieldInitializerListContext)._optField = _x } localctx.(*FieldInitializerListContext).fields = append(localctx.(*FieldInitializerListContext).fields, localctx.(*FieldInitializerListContext)._optField) { - p.SetState(199) + p.SetState(203) var _m = p.Match(CELParserCOLON) localctx.(*FieldInitializerListContext).s21 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*FieldInitializerListContext).cols = append(localctx.(*FieldInitializerListContext).cols, localctx.(*FieldInitializerListContext).s21) { - p.SetState(200) + p.SetState(204) var _x = p.Expr() - localctx.(*FieldInitializerListContext)._expr = _x } localctx.(*FieldInitializerListContext).values = append(localctx.(*FieldInitializerListContext).values, localctx.(*FieldInitializerListContext)._expr) - p.SetState(208) + p.SetState(212) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -4718,59 +4529,54 @@ func (p *CELParser) FieldInitializerList() (localctx IFieldInitializerListContex for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(201) + p.SetState(205) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(202) + p.SetState(206) var _x = p.OptField() - localctx.(*FieldInitializerListContext)._optField = _x } localctx.(*FieldInitializerListContext).fields = append(localctx.(*FieldInitializerListContext).fields, localctx.(*FieldInitializerListContext)._optField) { - p.SetState(203) + p.SetState(207) var _m = p.Match(CELParserCOLON) localctx.(*FieldInitializerListContext).s21 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*FieldInitializerListContext).cols = append(localctx.(*FieldInitializerListContext).cols, localctx.(*FieldInitializerListContext).s21) { - p.SetState(204) + p.SetState(208) var _x = p.Expr() - localctx.(*FieldInitializerListContext)._expr = _x } localctx.(*FieldInitializerListContext).values = append(localctx.(*FieldInitializerListContext).values, localctx.(*FieldInitializerListContext)._expr) - } - p.SetState(210) + p.SetState(214) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 28, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - errorExit: if p.HasError() { v := p.GetError() @@ -4784,7 +4590,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IOptFieldContext is an interface to support dynamic dispatch. type IOptFieldContext interface { antlr.ParserRuleContext @@ -4793,15 +4598,13 @@ type IOptFieldContext interface { GetParser() antlr.Parser // GetOpt returns the opt token. - GetOpt() antlr.Token - + GetOpt() antlr.Token // SetOpt sets the opt token. - SetOpt(antlr.Token) - + SetOpt(antlr.Token) // Getter signatures - IDENTIFIER() antlr.TerminalNode + EscapeIdent() IEscapeIdentContext QUESTIONMARK() antlr.TerminalNode // IsOptFieldContext differentiates from other interfaces. @@ -4811,7 +4614,7 @@ type IOptFieldContext interface { type OptFieldContext struct { antlr.BaseParserRuleContext parser antlr.Parser - opt antlr.Token + opt antlr.Token } func NewEmptyOptFieldContext() *OptFieldContext { @@ -4821,7 +4624,7 @@ func NewEmptyOptFieldContext() *OptFieldContext { return p } -func InitEmptyOptFieldContext(p *OptFieldContext) { +func InitEmptyOptFieldContext(p *OptFieldContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_optField } @@ -4843,12 +4646,22 @@ func (s *OptFieldContext) GetParser() antlr.Parser { return s.parser } func (s *OptFieldContext) GetOpt() antlr.Token { return s.opt } - func (s *OptFieldContext) SetOpt(v antlr.Token) { s.opt = v } +func (s *OptFieldContext) EscapeIdent() IEscapeIdentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEscapeIdentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } -func (s *OptFieldContext) IDENTIFIER() antlr.TerminalNode { - return s.GetToken(CELParserIDENTIFIER, 0) + if t == nil { + return nil + } + + return t.(IEscapeIdentContext) } func (s *OptFieldContext) QUESTIONMARK() antlr.TerminalNode { @@ -4863,7 +4676,6 @@ func (s *OptFieldContext) ToStringTree(ruleNames []string, recog antlr.Recognize return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *OptFieldContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterOptField(s) @@ -4886,48 +4698,38 @@ func (s *OptFieldContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) OptField() (localctx IOptFieldContext) { localctx = NewOptFieldContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 24, CELParserRULE_optField) var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(212) + p.SetState(216) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserQUESTIONMARK { { - p.SetState(211) + p.SetState(215) var _m = p.Match(CELParserQUESTIONMARK) localctx.(*OptFieldContext).opt = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(214) - p.Match(CELParserIDENTIFIER) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(218) + p.EscapeIdent() } - - errorExit: if p.HasError() { v := p.GetError() @@ -4941,7 +4743,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // IMapInitializerListContext is an interface to support dynamic dispatch. type IMapInitializerListContext interface { antlr.ParserRuleContext @@ -4950,48 +4751,40 @@ type IMapInitializerListContext interface { GetParser() antlr.Parser // GetS21 returns the s21 token. - GetS21() antlr.Token - + GetS21() antlr.Token // SetS21 sets the s21 token. - SetS21(antlr.Token) - + SetS21(antlr.Token) // GetCols returns the cols token list. GetCols() []antlr.Token - // SetCols sets the cols token list. SetCols([]antlr.Token) - // Get_optExpr returns the _optExpr rule contexts. Get_optExpr() IOptExprContext // Get_expr returns the _expr rule contexts. Get_expr() IExprContext - // Set_optExpr sets the _optExpr rule contexts. Set_optExpr(IOptExprContext) // Set_expr sets the _expr rule contexts. Set_expr(IExprContext) - // GetKeys returns the keys rule context list. GetKeys() []IOptExprContext // GetValues returns the values rule context list. GetValues() []IExprContext - // SetKeys sets the keys rule context list. - SetKeys([]IOptExprContext) + SetKeys([]IOptExprContext) // SetValues sets the values rule context list. - SetValues([]IExprContext) - + SetValues([]IExprContext) // Getter signatures AllOptExpr() []IOptExprContext @@ -5009,13 +4802,13 @@ type IMapInitializerListContext interface { type MapInitializerListContext struct { antlr.BaseParserRuleContext - parser antlr.Parser - _optExpr IOptExprContext - keys []IOptExprContext - s21 antlr.Token - cols []antlr.Token - _expr IExprContext - values []IExprContext + parser antlr.Parser + _optExpr IOptExprContext + keys []IOptExprContext + s21 antlr.Token + cols []antlr.Token + _expr IExprContext + values []IExprContext } func NewEmptyMapInitializerListContext() *MapInitializerListContext { @@ -5025,7 +4818,7 @@ func NewEmptyMapInitializerListContext() *MapInitializerListContext { return p } -func InitEmptyMapInitializerListContext(p *MapInitializerListContext) { +func InitEmptyMapInitializerListContext(p *MapInitializerListContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_mapInitializerList } @@ -5047,36 +4840,28 @@ func (s *MapInitializerListContext) GetParser() antlr.Parser { return s.parser } func (s *MapInitializerListContext) GetS21() antlr.Token { return s.s21 } - func (s *MapInitializerListContext) SetS21(v antlr.Token) { s.s21 = v } - func (s *MapInitializerListContext) GetCols() []antlr.Token { return s.cols } - func (s *MapInitializerListContext) SetCols(v []antlr.Token) { s.cols = v } - func (s *MapInitializerListContext) Get_optExpr() IOptExprContext { return s._optExpr } func (s *MapInitializerListContext) Get_expr() IExprContext { return s._expr } - func (s *MapInitializerListContext) Set_optExpr(v IOptExprContext) { s._optExpr = v } func (s *MapInitializerListContext) Set_expr(v IExprContext) { s._expr = v } - func (s *MapInitializerListContext) GetKeys() []IOptExprContext { return s.keys } func (s *MapInitializerListContext) GetValues() []IExprContext { return s.values } - func (s *MapInitializerListContext) SetKeys(v []IOptExprContext) { s.keys = v } func (s *MapInitializerListContext) SetValues(v []IExprContext) { s.values = v } - func (s *MapInitializerListContext) AllOptExpr() []IOptExprContext { children := s.GetChildren() len := 0 @@ -5099,12 +4884,12 @@ func (s *MapInitializerListContext) AllOptExpr() []IOptExprContext { } func (s *MapInitializerListContext) OptExpr(i int) IOptExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IOptExprContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -5148,12 +4933,12 @@ func (s *MapInitializerListContext) AllExpr() []IExprContext { } func (s *MapInitializerListContext) Expr(i int) IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext j := 0 for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { if j == i { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } j++ @@ -5183,7 +4968,6 @@ func (s *MapInitializerListContext) ToStringTree(ruleNames []string, recog antlr return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *MapInitializerListContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterMapInitializerList(s) @@ -5206,9 +4990,6 @@ func (s *MapInitializerListContext) Accept(visitor antlr.ParseTreeVisitor) inter } } - - - func (p *CELParser) MapInitializerList() (localctx IMapInitializerListContext) { localctx = NewMapInitializerListContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 26, CELParserRULE_mapInitializerList) @@ -5216,36 +4997,34 @@ func (p *CELParser) MapInitializerList() (localctx IMapInitializerListContext) { p.EnterOuterAlt(localctx, 1) { - p.SetState(216) + p.SetState(220) var _x = p.OptExpr() - localctx.(*MapInitializerListContext)._optExpr = _x } localctx.(*MapInitializerListContext).keys = append(localctx.(*MapInitializerListContext).keys, localctx.(*MapInitializerListContext)._optExpr) { - p.SetState(217) + p.SetState(221) var _m = p.Match(CELParserCOLON) localctx.(*MapInitializerListContext).s21 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*MapInitializerListContext).cols = append(localctx.(*MapInitializerListContext).cols, localctx.(*MapInitializerListContext).s21) { - p.SetState(218) + p.SetState(222) var _x = p.Expr() - localctx.(*MapInitializerListContext)._expr = _x } localctx.(*MapInitializerListContext).values = append(localctx.(*MapInitializerListContext).values, localctx.(*MapInitializerListContext)._expr) - p.SetState(226) + p.SetState(230) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -5257,59 +5036,54 @@ func (p *CELParser) MapInitializerList() (localctx IMapInitializerListContext) { for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { if _alt == 1 { { - p.SetState(219) + p.SetState(223) p.Match(CELParserCOMMA) if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } { - p.SetState(220) + p.SetState(224) var _x = p.OptExpr() - localctx.(*MapInitializerListContext)._optExpr = _x } localctx.(*MapInitializerListContext).keys = append(localctx.(*MapInitializerListContext).keys, localctx.(*MapInitializerListContext)._optExpr) { - p.SetState(221) + p.SetState(225) var _m = p.Match(CELParserCOLON) localctx.(*MapInitializerListContext).s21 = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } localctx.(*MapInitializerListContext).cols = append(localctx.(*MapInitializerListContext).cols, localctx.(*MapInitializerListContext).s21) { - p.SetState(222) + p.SetState(226) var _x = p.Expr() - localctx.(*MapInitializerListContext)._expr = _x } localctx.(*MapInitializerListContext).values = append(localctx.(*MapInitializerListContext).values, localctx.(*MapInitializerListContext)._expr) - } - p.SetState(228) + p.SetState(232) p.GetErrorHandler().Sync(p) if p.HasError() { - goto errorExit - } + goto errorExit + } _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 30, p.GetParserRuleContext()) if p.HasError() { goto errorExit } } - - errorExit: if p.HasError() { v := p.GetError() @@ -5323,6 +5097,215 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } +// IEscapeIdentContext is an interface to support dynamic dispatch. +type IEscapeIdentContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + // IsEscapeIdentContext differentiates from other interfaces. + IsEscapeIdentContext() +} + +type EscapeIdentContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyEscapeIdentContext() *EscapeIdentContext { + var p = new(EscapeIdentContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = CELParserRULE_escapeIdent + return p +} + +func InitEmptyEscapeIdentContext(p *EscapeIdentContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = CELParserRULE_escapeIdent +} + +func (*EscapeIdentContext) IsEscapeIdentContext() {} + +func NewEscapeIdentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EscapeIdentContext { + var p = new(EscapeIdentContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = CELParserRULE_escapeIdent + + return p +} + +func (s *EscapeIdentContext) GetParser() antlr.Parser { return s.parser } + +func (s *EscapeIdentContext) CopyAll(ctx *EscapeIdentContext) { + s.CopyFrom(&ctx.BaseParserRuleContext) +} + +func (s *EscapeIdentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EscapeIdentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +type EscapedIdentifierContext struct { + EscapeIdentContext + id antlr.Token +} + +func NewEscapedIdentifierContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *EscapedIdentifierContext { + var p = new(EscapedIdentifierContext) + + InitEmptyEscapeIdentContext(&p.EscapeIdentContext) + p.parser = parser + p.CopyAll(ctx.(*EscapeIdentContext)) + + return p +} + +func (s *EscapedIdentifierContext) GetId() antlr.Token { return s.id } + +func (s *EscapedIdentifierContext) SetId(v antlr.Token) { s.id = v } + +func (s *EscapedIdentifierContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EscapedIdentifierContext) ESC_IDENTIFIER() antlr.TerminalNode { + return s.GetToken(CELParserESC_IDENTIFIER, 0) +} + +func (s *EscapedIdentifierContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.EnterEscapedIdentifier(s) + } +} + +func (s *EscapedIdentifierContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.ExitEscapedIdentifier(s) + } +} + +func (s *EscapedIdentifierContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { + switch t := visitor.(type) { + case CELVisitor: + return t.VisitEscapedIdentifier(s) + + default: + return t.VisitChildren(s) + } +} + +type SimpleIdentifierContext struct { + EscapeIdentContext + id antlr.Token +} + +func NewSimpleIdentifierContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *SimpleIdentifierContext { + var p = new(SimpleIdentifierContext) + + InitEmptyEscapeIdentContext(&p.EscapeIdentContext) + p.parser = parser + p.CopyAll(ctx.(*EscapeIdentContext)) + + return p +} + +func (s *SimpleIdentifierContext) GetId() antlr.Token { return s.id } + +func (s *SimpleIdentifierContext) SetId(v antlr.Token) { s.id = v } + +func (s *SimpleIdentifierContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SimpleIdentifierContext) IDENTIFIER() antlr.TerminalNode { + return s.GetToken(CELParserIDENTIFIER, 0) +} + +func (s *SimpleIdentifierContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.EnterSimpleIdentifier(s) + } +} + +func (s *SimpleIdentifierContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(CELListener); ok { + listenerT.ExitSimpleIdentifier(s) + } +} + +func (s *SimpleIdentifierContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { + switch t := visitor.(type) { + case CELVisitor: + return t.VisitSimpleIdentifier(s) + + default: + return t.VisitChildren(s) + } +} + +func (p *CELParser) EscapeIdent() (localctx IEscapeIdentContext) { + localctx = NewEscapeIdentContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 28, CELParserRULE_escapeIdent) + p.SetState(235) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetTokenStream().LA(1) { + case CELParserIDENTIFIER: + localctx = NewSimpleIdentifierContext(p, localctx) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(233) + + var _m = p.Match(CELParserIDENTIFIER) + + localctx.(*SimpleIdentifierContext).id = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + case CELParserESC_IDENTIFIER: + localctx = NewEscapedIdentifierContext(p, localctx) + p.EnterOuterAlt(localctx, 2) + { + p.SetState(234) + + var _m = p.Match(CELParserESC_IDENTIFIER) + + localctx.(*EscapedIdentifierContext).id = _m + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} // IOptExprContext is an interface to support dynamic dispatch. type IOptExprContext interface { @@ -5332,21 +5315,17 @@ type IOptExprContext interface { GetParser() antlr.Parser // GetOpt returns the opt token. - GetOpt() antlr.Token - + GetOpt() antlr.Token // SetOpt sets the opt token. - SetOpt(antlr.Token) - + SetOpt(antlr.Token) // GetE returns the e rule contexts. GetE() IExprContext - // SetE sets the e rule contexts. SetE(IExprContext) - // Getter signatures Expr() IExprContext QUESTIONMARK() antlr.TerminalNode @@ -5358,8 +5337,8 @@ type IOptExprContext interface { type OptExprContext struct { antlr.BaseParserRuleContext parser antlr.Parser - opt antlr.Token - e IExprContext + opt antlr.Token + e IExprContext } func NewEmptyOptExprContext() *OptExprContext { @@ -5369,7 +5348,7 @@ func NewEmptyOptExprContext() *OptExprContext { return p } -func InitEmptyOptExprContext(p *OptExprContext) { +func InitEmptyOptExprContext(p *OptExprContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_optExpr } @@ -5391,21 +5370,17 @@ func (s *OptExprContext) GetParser() antlr.Parser { return s.parser } func (s *OptExprContext) GetOpt() antlr.Token { return s.opt } - func (s *OptExprContext) SetOpt(v antlr.Token) { s.opt = v } - func (s *OptExprContext) GetE() IExprContext { return s.e } - func (s *OptExprContext) SetE(v IExprContext) { s.e = v } - func (s *OptExprContext) Expr() IExprContext { - var t antlr.RuleContext; + var t antlr.RuleContext for _, ctx := range s.GetChildren() { if _, ok := ctx.(IExprContext); ok { - t = ctx.(antlr.RuleContext); + t = ctx.(antlr.RuleContext) break } } @@ -5429,7 +5404,6 @@ func (s *OptExprContext) ToStringTree(ruleNames []string, recog antlr.Recognizer return antlr.TreesStringTree(s, ruleNames, recog) } - func (s *OptExprContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterOptExpr(s) @@ -5452,48 +5426,41 @@ func (s *OptExprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - - func (p *CELParser) OptExpr() (localctx IOptExprContext) { localctx = NewOptExprContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 28, CELParserRULE_optExpr) + p.EnterRule(localctx, 30, CELParserRULE_optExpr) var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(230) + p.SetState(238) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserQUESTIONMARK { { - p.SetState(229) + p.SetState(237) var _m = p.Match(CELParserQUESTIONMARK) localctx.(*OptExprContext).opt = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(232) + p.SetState(240) var _x = p.Expr() - localctx.(*OptExprContext).e = _x } - - errorExit: if p.HasError() { v := p.GetError() @@ -5507,7 +5474,6 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - // ILiteralContext is an interface to support dynamic dispatch. type ILiteralContext interface { antlr.ParserRuleContext @@ -5530,7 +5496,7 @@ func NewEmptyLiteralContext() *LiteralContext { return p } -func InitEmptyLiteralContext(p *LiteralContext) { +func InitEmptyLiteralContext(p *LiteralContext) { antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) p.RuleIndex = CELParserRULE_literal } @@ -5562,9 +5528,6 @@ func (s *LiteralContext) ToStringTree(ruleNames []string, recog antlr.Recognizer return antlr.TreesStringTree(s, ruleNames, recog) } - - - type BytesContext struct { LiteralContext tok antlr.Token @@ -5580,10 +5543,8 @@ func NewBytesContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *BytesCon return p } - func (s *BytesContext) GetTok() antlr.Token { return s.tok } - func (s *BytesContext) SetTok(v antlr.Token) { s.tok = v } func (s *BytesContext) GetRuleContext() antlr.RuleContext { @@ -5594,7 +5555,6 @@ func (s *BytesContext) BYTES() antlr.TerminalNode { return s.GetToken(CELParserBYTES, 0) } - func (s *BytesContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterBytes(s) @@ -5617,7 +5577,6 @@ func (s *BytesContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type UintContext struct { LiteralContext tok antlr.Token @@ -5633,10 +5592,8 @@ func NewUintContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *UintConte return p } - func (s *UintContext) GetTok() antlr.Token { return s.tok } - func (s *UintContext) SetTok(v antlr.Token) { s.tok = v } func (s *UintContext) GetRuleContext() antlr.RuleContext { @@ -5647,7 +5604,6 @@ func (s *UintContext) NUM_UINT() antlr.TerminalNode { return s.GetToken(CELParserNUM_UINT, 0) } - func (s *UintContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterUint(s) @@ -5670,7 +5626,6 @@ func (s *UintContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type NullContext struct { LiteralContext tok antlr.Token @@ -5686,10 +5641,8 @@ func NewNullContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *NullConte return p } - func (s *NullContext) GetTok() antlr.Token { return s.tok } - func (s *NullContext) SetTok(v antlr.Token) { s.tok = v } func (s *NullContext) GetRuleContext() antlr.RuleContext { @@ -5700,7 +5653,6 @@ func (s *NullContext) NUL() antlr.TerminalNode { return s.GetToken(CELParserNUL, 0) } - func (s *NullContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterNull(s) @@ -5723,7 +5675,6 @@ func (s *NullContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type BoolFalseContext struct { LiteralContext tok antlr.Token @@ -5739,10 +5690,8 @@ func NewBoolFalseContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *Bool return p } - func (s *BoolFalseContext) GetTok() antlr.Token { return s.tok } - func (s *BoolFalseContext) SetTok(v antlr.Token) { s.tok = v } func (s *BoolFalseContext) GetRuleContext() antlr.RuleContext { @@ -5753,7 +5702,6 @@ func (s *BoolFalseContext) CEL_FALSE() antlr.TerminalNode { return s.GetToken(CELParserCEL_FALSE, 0) } - func (s *BoolFalseContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterBoolFalse(s) @@ -5776,7 +5724,6 @@ func (s *BoolFalseContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type StringContext struct { LiteralContext tok antlr.Token @@ -5792,10 +5739,8 @@ func NewStringContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *StringC return p } - func (s *StringContext) GetTok() antlr.Token { return s.tok } - func (s *StringContext) SetTok(v antlr.Token) { s.tok = v } func (s *StringContext) GetRuleContext() antlr.RuleContext { @@ -5806,7 +5751,6 @@ func (s *StringContext) STRING() antlr.TerminalNode { return s.GetToken(CELParserSTRING, 0) } - func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterString(s) @@ -5829,11 +5773,10 @@ func (s *StringContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type DoubleContext struct { LiteralContext sign antlr.Token - tok antlr.Token + tok antlr.Token } func NewDoubleContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *DoubleContext { @@ -5846,12 +5789,10 @@ func NewDoubleContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *DoubleC return p } - func (s *DoubleContext) GetSign() antlr.Token { return s.sign } func (s *DoubleContext) GetTok() antlr.Token { return s.tok } - func (s *DoubleContext) SetSign(v antlr.Token) { s.sign = v } func (s *DoubleContext) SetTok(v antlr.Token) { s.tok = v } @@ -5868,7 +5809,6 @@ func (s *DoubleContext) MINUS() antlr.TerminalNode { return s.GetToken(CELParserMINUS, 0) } - func (s *DoubleContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterDouble(s) @@ -5891,7 +5831,6 @@ func (s *DoubleContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type BoolTrueContext struct { LiteralContext tok antlr.Token @@ -5907,10 +5846,8 @@ func NewBoolTrueContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *BoolT return p } - func (s *BoolTrueContext) GetTok() antlr.Token { return s.tok } - func (s *BoolTrueContext) SetTok(v antlr.Token) { s.tok = v } func (s *BoolTrueContext) GetRuleContext() antlr.RuleContext { @@ -5921,7 +5858,6 @@ func (s *BoolTrueContext) CEL_TRUE() antlr.TerminalNode { return s.GetToken(CELParserCEL_TRUE, 0) } - func (s *BoolTrueContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterBoolTrue(s) @@ -5944,11 +5880,10 @@ func (s *BoolTrueContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - type IntContext struct { LiteralContext sign antlr.Token - tok antlr.Token + tok antlr.Token } func NewIntContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IntContext { @@ -5961,12 +5896,10 @@ func NewIntContext(parser antlr.Parser, ctx antlr.ParserRuleContext) *IntContext return p } - func (s *IntContext) GetSign() antlr.Token { return s.sign } func (s *IntContext) GetTok() antlr.Token { return s.tok } - func (s *IntContext) SetSign(v antlr.Token) { s.sign = v } func (s *IntContext) SetTok(v antlr.Token) { s.tok = v } @@ -5983,7 +5916,6 @@ func (s *IntContext) MINUS() antlr.TerminalNode { return s.GetToken(CELParserMINUS, 0) } - func (s *IntContext) EnterRule(listener antlr.ParseTreeListener) { if listenerT, ok := listener.(CELListener); ok { listenerT.EnterInt(s) @@ -6006,188 +5938,177 @@ func (s *IntContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { } } - - func (p *CELParser) Literal() (localctx ILiteralContext) { localctx = NewLiteralContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 30, CELParserRULE_literal) + p.EnterRule(localctx, 32, CELParserRULE_literal) var _la int - p.SetState(248) + p.SetState(256) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 34, p.GetParserRuleContext()) { + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 35, p.GetParserRuleContext()) { case 1: localctx = NewIntContext(p, localctx) p.EnterOuterAlt(localctx, 1) - p.SetState(235) + p.SetState(243) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserMINUS { { - p.SetState(234) + p.SetState(242) var _m = p.Match(CELParserMINUS) localctx.(*IntContext).sign = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(237) + p.SetState(245) var _m = p.Match(CELParserNUM_INT) localctx.(*IntContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 2: localctx = NewUintContext(p, localctx) p.EnterOuterAlt(localctx, 2) { - p.SetState(238) + p.SetState(246) var _m = p.Match(CELParserNUM_UINT) localctx.(*UintContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 3: localctx = NewDoubleContext(p, localctx) p.EnterOuterAlt(localctx, 3) - p.SetState(240) + p.SetState(248) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - if _la == CELParserMINUS { { - p.SetState(239) + p.SetState(247) var _m = p.Match(CELParserMINUS) localctx.(*DoubleContext).sign = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } } { - p.SetState(242) + p.SetState(250) var _m = p.Match(CELParserNUM_FLOAT) localctx.(*DoubleContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 4: localctx = NewStringContext(p, localctx) p.EnterOuterAlt(localctx, 4) { - p.SetState(243) + p.SetState(251) var _m = p.Match(CELParserSTRING) localctx.(*StringContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 5: localctx = NewBytesContext(p, localctx) p.EnterOuterAlt(localctx, 5) { - p.SetState(244) + p.SetState(252) var _m = p.Match(CELParserBYTES) localctx.(*BytesContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 6: localctx = NewBoolTrueContext(p, localctx) p.EnterOuterAlt(localctx, 6) { - p.SetState(245) + p.SetState(253) var _m = p.Match(CELParserCEL_TRUE) localctx.(*BoolTrueContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 7: localctx = NewBoolFalseContext(p, localctx) p.EnterOuterAlt(localctx, 7) { - p.SetState(246) + p.SetState(254) var _m = p.Match(CELParserCEL_FALSE) localctx.(*BoolFalseContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } - case 8: localctx = NewNullContext(p, localctx) p.EnterOuterAlt(localctx, 8) { - p.SetState(247) + p.SetState(255) var _m = p.Match(CELParserNUL) localctx.(*NullContext).tok = _m if p.HasError() { - // Recognition error - abort rule - goto errorExit + // Recognition error - abort rule + goto errorExit } } @@ -6195,7 +6116,6 @@ func (p *CELParser) Literal() (localctx ILiteralContext) { goto errorExit } - errorExit: if p.HasError() { v := p.GetError() @@ -6209,24 +6129,28 @@ errorExit: goto errorExit // Trick to prevent compiler error if the label is not used } - func (p *CELParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int) bool { switch ruleIndex { case 4: - var t *RelationContext = nil - if localctx != nil { t = localctx.(*RelationContext) } - return p.Relation_Sempred(t, predIndex) + var t *RelationContext = nil + if localctx != nil { + t = localctx.(*RelationContext) + } + return p.Relation_Sempred(t, predIndex) case 5: - var t *CalcContext = nil - if localctx != nil { t = localctx.(*CalcContext) } - return p.Calc_Sempred(t, predIndex) + var t *CalcContext = nil + if localctx != nil { + t = localctx.(*CalcContext) + } + return p.Calc_Sempred(t, predIndex) case 7: - var t *MemberContext = nil - if localctx != nil { t = localctx.(*MemberContext) } - return p.Member_Sempred(t, predIndex) - + var t *MemberContext = nil + if localctx != nil { + t = localctx.(*MemberContext) + } + return p.Member_Sempred(t, predIndex) default: panic("No predicate with index: " + fmt.Sprint(ruleIndex)) @@ -6236,7 +6160,7 @@ func (p *CELParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex int func (p *CELParser) Relation_Sempred(localctx antlr.RuleContext, predIndex int) bool { switch predIndex { case 0: - return p.Precpred(p.GetParserRuleContext(), 1) + return p.Precpred(p.GetParserRuleContext(), 1) default: panic("No predicate with index: " + fmt.Sprint(predIndex)) @@ -6246,10 +6170,10 @@ func (p *CELParser) Relation_Sempred(localctx antlr.RuleContext, predIndex int) func (p *CELParser) Calc_Sempred(localctx antlr.RuleContext, predIndex int) bool { switch predIndex { case 1: - return p.Precpred(p.GetParserRuleContext(), 2) + return p.Precpred(p.GetParserRuleContext(), 2) case 2: - return p.Precpred(p.GetParserRuleContext(), 1) + return p.Precpred(p.GetParserRuleContext(), 1) default: panic("No predicate with index: " + fmt.Sprint(predIndex)) @@ -6259,16 +6183,15 @@ func (p *CELParser) Calc_Sempred(localctx antlr.RuleContext, predIndex int) bool func (p *CELParser) Member_Sempred(localctx antlr.RuleContext, predIndex int) bool { switch predIndex { case 3: - return p.Precpred(p.GetParserRuleContext(), 3) + return p.Precpred(p.GetParserRuleContext(), 3) case 4: - return p.Precpred(p.GetParserRuleContext(), 2) + return p.Precpred(p.GetParserRuleContext(), 2) case 5: - return p.Precpred(p.GetParserRuleContext(), 1) + return p.Precpred(p.GetParserRuleContext(), 1) default: panic("No predicate with index: " + fmt.Sprint(predIndex)) } } - diff --git a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_visitor.go b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_visitor.go index d2fbd563a..7cefe5c57 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/gen/cel_visitor.go +++ b/e2e/vendor/github.com/google/cel-go/parser/gen/cel_visitor.go @@ -1,9 +1,8 @@ -// Code generated from /usr/local/google/home/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. +// Code generated from /usr/local/google/home/jdtatum/github/cel-go/parser/gen/CEL.g4 by ANTLR 4.13.1. DO NOT EDIT. package gen // CEL import "github.com/antlr4-go/antlr/v4" - // A complete Visitor for a parse tree produced by CELParser. type CELVisitor interface { antlr.ParseTreeVisitor @@ -47,8 +46,11 @@ type CELVisitor interface { // Visit a parse tree produced by CELParser#Index. VisitIndex(ctx *IndexContext) interface{} - // Visit a parse tree produced by CELParser#IdentOrGlobalCall. - VisitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) interface{} + // Visit a parse tree produced by CELParser#Ident. + VisitIdent(ctx *IdentContext) interface{} + + // Visit a parse tree produced by CELParser#GlobalCall. + VisitGlobalCall(ctx *GlobalCallContext) interface{} // Visit a parse tree produced by CELParser#Nested. VisitNested(ctx *NestedContext) interface{} @@ -80,6 +82,12 @@ type CELVisitor interface { // Visit a parse tree produced by CELParser#mapInitializerList. VisitMapInitializerList(ctx *MapInitializerListContext) interface{} + // Visit a parse tree produced by CELParser#SimpleIdentifier. + VisitSimpleIdentifier(ctx *SimpleIdentifierContext) interface{} + + // Visit a parse tree produced by CELParser#EscapedIdentifier. + VisitEscapedIdentifier(ctx *EscapedIdentifierContext) interface{} + // Visit a parse tree produced by CELParser#optExpr. VisitOptExpr(ctx *OptExprContext) interface{} @@ -106,5 +114,4 @@ type CELVisitor interface { // Visit a parse tree produced by CELParser#Null. VisitNull(ctx *NullContext) interface{} - -} \ No newline at end of file +} diff --git a/e2e/vendor/github.com/google/cel-go/parser/helper.go b/e2e/vendor/github.com/google/cel-go/parser/helper.go index 9f09ead0e..c13296dd5 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/helper.go +++ b/e2e/vendor/github.com/google/cel-go/parser/helper.go @@ -470,6 +470,11 @@ func (e *exprHelper) NewAccuIdent() ast.Expr { return e.exprFactory.NewAccuIdent(e.nextMacroID()) } +// AccuIdentName implements the ExprHelper interface method. +func (e *exprHelper) AccuIdentName() string { + return e.exprFactory.AccuIdentName() +} + // NewGlobalCall implements the ExprHelper interface method. func (e *exprHelper) NewCall(function string, args ...ast.Expr) ast.Expr { return e.exprFactory.NewCall(e.nextMacroID(), function, args...) diff --git a/e2e/vendor/github.com/google/cel-go/parser/macro.go b/e2e/vendor/github.com/google/cel-go/parser/macro.go index dc47b4203..6b3b648d3 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/macro.go +++ b/e2e/vendor/github.com/google/cel-go/parser/macro.go @@ -225,6 +225,9 @@ type ExprHelper interface { // NewAccuIdent returns an accumulator identifier for use with comprehension results. NewAccuIdent() ast.Expr + // AccuIdentName returns the name of the accumulator identifier. + AccuIdentName() string + // NewCall creates a function call Expr value for a global (free) function. NewCall(function string, args ...ast.Expr) ast.Expr @@ -259,8 +262,13 @@ var ( // ExistsOneMacro expands "range.exists_one(var, predicate)", which is true if for exactly one // element in range the predicate holds. + // Deprecated: Use ExistsOneMacroNew ExistsOneMacro = NewReceiverMacro(operators.ExistsOne, 2, MakeExistsOne) + // ExistsOneMacroNew expands "range.existsOne(var, predicate)", which is true if for exactly one + // element in range the predicate holds. + ExistsOneMacroNew = NewReceiverMacro("existsOne", 2, MakeExistsOne) + // MapMacro expands "range.map(var, function)" into a comprehension which applies the function // to each element in the range to produce a new list. MapMacro = NewReceiverMacro(operators.Map, 2, MakeMap) @@ -280,6 +288,7 @@ var ( AllMacro, ExistsMacro, ExistsOneMacro, + ExistsOneMacroNew, MapMacro, MapFilterMacro, FilterMacro, @@ -292,6 +301,11 @@ var ( // AccumulatorName is the traditional variable name assigned to the fold accumulator variable. const AccumulatorName = "__result__" +// HiddenAccumulatorName is a proposed update to the default fold accumlator variable. +// @result is not normally accessible from source, preventing accidental or intentional collisions +// in user expressions. +const HiddenAccumulatorName = "@result" + type quantifierKind int const ( @@ -336,6 +350,10 @@ func MakeMap(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common if !found { return nil, eh.NewError(args[0].ID(), "argument is not an identifier") } + accu := eh.AccuIdentName() + if v == accu || v == AccumulatorName { + return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable") + } var fn ast.Expr var filter ast.Expr @@ -355,7 +373,7 @@ func MakeMap(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common if filter != nil { step = eh.NewCall(operators.Conditional, filter, step, eh.NewAccuIdent()) } - return eh.NewComprehension(target, v, AccumulatorName, init, condition, step, eh.NewAccuIdent()), nil + return eh.NewComprehension(target, v, accu, init, condition, step, eh.NewAccuIdent()), nil } // MakeFilter expands the input call arguments into a comprehension which produces a list which contains @@ -366,13 +384,17 @@ func MakeFilter(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *com if !found { return nil, eh.NewError(args[0].ID(), "argument is not an identifier") } + accu := eh.AccuIdentName() + if v == accu || v == AccumulatorName { + return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable") + } filter := args[1] init := eh.NewList() condition := eh.NewLiteral(types.True) step := eh.NewCall(operators.Add, eh.NewAccuIdent(), eh.NewList(args[0])) step = eh.NewCall(operators.Conditional, filter, step, eh.NewAccuIdent()) - return eh.NewComprehension(target, v, AccumulatorName, init, condition, step, eh.NewAccuIdent()), nil + return eh.NewComprehension(target, v, accu, init, condition, step, eh.NewAccuIdent()), nil } // MakeHas expands the input call arguments into a presence test, e.g. has(.field) @@ -389,6 +411,10 @@ func makeQuantifier(kind quantifierKind, eh ExprHelper, target ast.Expr, args [] if !found { return nil, eh.NewError(args[0].ID(), "argument must be a simple name") } + accu := eh.AccuIdentName() + if v == accu || v == AccumulatorName { + return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable") + } var init ast.Expr var condition ast.Expr @@ -416,7 +442,7 @@ func makeQuantifier(kind quantifierKind, eh ExprHelper, target ast.Expr, args [] default: return nil, eh.NewError(args[0].ID(), fmt.Sprintf("unrecognized quantifier '%v'", kind)) } - return eh.NewComprehension(target, v, AccumulatorName, init, condition, step, result), nil + return eh.NewComprehension(target, v, accu, init, condition, step, result), nil } func extractIdent(e ast.Expr) (string, bool) { diff --git a/e2e/vendor/github.com/google/cel-go/parser/options.go b/e2e/vendor/github.com/google/cel-go/parser/options.go index 61fc3adec..4eb30f83e 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/options.go +++ b/e2e/vendor/github.com/google/cel-go/parser/options.go @@ -26,6 +26,8 @@ type options struct { populateMacroCalls bool enableOptionalSyntax bool enableVariadicOperatorASTs bool + enableIdentEscapeSyntax bool + enableHiddenAccumulatorName bool } // Option configures the behavior of the parser. @@ -127,6 +129,27 @@ func EnableOptionalSyntax(optionalSyntax bool) Option { } } +// EnableIdentEscapeSyntax enables backtick (`) escaped field identifiers. This +// supports extended types of characters in identifiers, e.g. foo.`baz-bar`. +func EnableIdentEscapeSyntax(enableIdentEscapeSyntax bool) Option { + return func(opts *options) error { + opts.enableIdentEscapeSyntax = enableIdentEscapeSyntax + return nil + } +} + +// EnableHiddenAccumulatorName uses an accumulator variable name that is not a +// normally accessible identifier in source for comprehension macros. Compatibility notes: +// with this option enabled, a parsed AST would be semantically the same as if disabled, but would +// have different internal identifiers in any of the built-in comprehension sub-expressions. When +// disabled, it is possible but almost certainly a logic error to access the accumulator variable. +func EnableHiddenAccumulatorName(enabled bool) Option { + return func(opts *options) error { + opts.enableHiddenAccumulatorName = enabled + return nil + } +} + // EnableVariadicOperatorASTs enables a compact representation of chained like-kind commutative // operators. e.g. `a || b || c || d` -> `call(op='||', args=[a, b, c, d])` // diff --git a/e2e/vendor/github.com/google/cel-go/parser/parser.go b/e2e/vendor/github.com/google/cel-go/parser/parser.go index 5cbb17672..b5ec73ec6 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/parser.go +++ b/e2e/vendor/github.com/google/cel-go/parser/parser.go @@ -17,6 +17,7 @@ package parser import ( + "errors" "fmt" "regexp" "strconv" @@ -40,6 +41,7 @@ type Parser struct { // NewParser builds and returns a new Parser using the provided options. func NewParser(opts ...Option) (*Parser, error) { p := &Parser{} + p.enableHiddenAccumulatorName = true for _, opt := range opts { if err := opt(&p.options); err != nil { return nil, err @@ -88,7 +90,11 @@ func mustNewParser(opts ...Option) *Parser { // Parse parses the expression represented by source and returns the result. func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { errs := common.NewErrors(source) - fac := ast.NewExprFactory() + accu := AccumulatorName + if p.enableHiddenAccumulatorName { + accu = HiddenAccumulatorName + } + fac := ast.NewExprFactoryWithAccumulator(accu) impl := parser{ errors: &parseErrors{errs}, exprFactory: fac, @@ -101,6 +107,7 @@ func (p *Parser) Parse(source common.Source) (*ast.AST, *common.Errors) { populateMacroCalls: p.populateMacroCalls, enableOptionalSyntax: p.enableOptionalSyntax, enableVariadicOperatorASTs: p.enableVariadicOperatorASTs, + enableIdentEscapeSyntax: p.enableIdentEscapeSyntax, } buf, ok := source.(runes.Buffer) if !ok { @@ -143,6 +150,27 @@ var reservedIds = map[string]struct{}{ "while": {}, } +func unescapeIdent(in string) (string, error) { + if len(in) <= 2 { + return "", errors.New("invalid escaped identifier: underflow") + } + return in[1 : len(in)-1], nil +} + +// normalizeIdent returns the interpreted identifier. +func (p *parser) normalizeIdent(ctx gen.IEscapeIdentContext) (string, error) { + switch ident := ctx.(type) { + case *gen.SimpleIdentifierContext: + return ident.GetId().GetText(), nil + case *gen.EscapedIdentifierContext: + if !p.enableIdentEscapeSyntax { + return "", errors.New("unsupported syntax: '`'") + } + return unescapeIdent(ident.GetId().GetText()) + } + return "", errors.New("unsupported ident kind") +} + // Parse converts a source input a parsed expression. // This function calls ParseWithMacros with AllMacros. // @@ -296,6 +324,7 @@ type parser struct { populateMacroCalls bool enableOptionalSyntax bool enableVariadicOperatorASTs bool + enableIdentEscapeSyntax bool } var _ gen.CELVisitor = (*parser)(nil) @@ -369,8 +398,10 @@ func (p *parser) Visit(tree antlr.ParseTree) any { return out case *gen.LogicalNotContext: return p.VisitLogicalNot(tree) - case *gen.IdentOrGlobalCallContext: - return p.VisitIdentOrGlobalCall(tree) + case *gen.IdentContext: + return p.VisitIdent(tree) + case *gen.GlobalCallContext: + return p.VisitGlobalCall(tree) case *gen.SelectContext: p.checkAndIncrementRecursionDepth() out := p.VisitSelect(tree) @@ -538,7 +569,10 @@ func (p *parser) VisitSelect(ctx *gen.SelectContext) any { if ctx.GetId() == nil || ctx.GetOp() == nil { return p.helper.newExpr(ctx) } - id := ctx.GetId().GetText() + id, err := p.normalizeIdent(ctx.GetId()) + if err != nil { + p.reportError(ctx.GetId(), "%v", err) + } if ctx.GetOpt() != nil { if !p.enableOptionalSyntax { return p.reportError(ctx.GetOp(), "unsupported syntax '.?'") @@ -622,12 +656,14 @@ func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext p.reportError(optField, "unsupported syntax '?'") continue } + // The field may be empty due to a prior error. - id := optField.IDENTIFIER() - if id == nil { - return []ast.EntryExpr{} + fieldName, err := p.normalizeIdent(optField.EscapeIdent()) + if err != nil { + p.reportError(ctx, "%v", err) + continue } - fieldName := id.GetText() + value := p.Visit(vals[i]).(ast.Expr) field := p.helper.newObjectField(initID, fieldName, value, optional) result[i] = field @@ -635,8 +671,8 @@ func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext return result } -// Visit a parse tree produced by CELParser#IdentOrGlobalCall. -func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) any { +// Visit a parse tree produced by CELParser#Ident. +func (p *parser) VisitIdent(ctx *gen.IdentContext) any { identName := "" if ctx.GetLeadingDot() != nil { identName = "." @@ -651,13 +687,30 @@ func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) any { return p.reportError(ctx, "reserved identifier: %s", id) } identName += id - if ctx.GetOp() != nil { - opID := p.helper.id(ctx.GetOp()) - return p.globalCallOrMacro(opID, identName, p.visitExprList(ctx.GetArgs())...) - } return p.helper.newIdent(ctx.GetId(), identName) } +// Visit a parse tree produced by CELParser#GlobalCallContext. +func (p *parser) VisitGlobalCall(ctx *gen.GlobalCallContext) any { + identName := "" + if ctx.GetLeadingDot() != nil { + identName = "." + } + // Handle the error case where no valid identifier is specified. + if ctx.GetId() == nil { + return p.helper.newExpr(ctx) + } + // Handle reserved identifiers. + id := ctx.GetId().GetText() + if _, ok := reservedIds[id]; ok { + return p.reportError(ctx, "reserved identifier: %s", id) + } + identName += id + opID := p.helper.id(ctx.GetOp()) + return p.globalCallOrMacro(opID, identName, p.visitExprList(ctx.GetArgs())...) + +} + // Visit a parse tree produced by CELParser#CreateList. func (p *parser) VisitCreateList(ctx *gen.CreateListContext) any { listID := p.helper.id(ctx.GetOp()) @@ -756,7 +809,7 @@ func (p *parser) VisitDouble(ctx *gen.DoubleContext) any { // Visit a parse tree produced by CELParser#String. func (p *parser) VisitString(ctx *gen.StringContext) any { - s := p.unquote(ctx, ctx.GetText(), false) + s := p.unquote(ctx, ctx.GetTok().GetText(), false) return p.helper.newLiteralString(ctx, s) } @@ -922,7 +975,7 @@ func (p *parser) expandMacro(exprID int64, function string, target ast.Expr, arg loc = p.helper.getLocation(exprID) } p.helper.deleteID(exprID) - return p.reportError(loc, err.Message), true + return p.reportError(loc, "%s", err.Message), true } // A nil value from the macro indicates that the macro implementation decided that // an expansion should not be performed. diff --git a/e2e/vendor/github.com/google/cel-go/parser/unescape.go b/e2e/vendor/github.com/google/cel-go/parser/unescape.go index 27c57a9f3..43cc9b901 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/unescape.go +++ b/e2e/vendor/github.com/google/cel-go/parser/unescape.go @@ -15,7 +15,7 @@ package parser import ( - "fmt" + "errors" "strings" "unicode/utf8" ) @@ -30,7 +30,7 @@ func unescape(value string, isBytes bool) (string, error) { // Nothing to unescape / decode. if n < 2 { - return value, fmt.Errorf("unable to unescape string") + return value, errors.New("unable to unescape string") } // Raw string preceded by the 'r|R' prefix. @@ -43,7 +43,7 @@ func unescape(value string, isBytes bool) (string, error) { // Quoted string of some form, must have same first and last char. if value[0] != value[n-1] || (value[0] != '"' && value[0] != '\'') { - return value, fmt.Errorf("unable to unescape string") + return value, errors.New("unable to unescape string") } // Normalize the multi-line CEL string representation to a standard @@ -51,12 +51,12 @@ func unescape(value string, isBytes bool) (string, error) { if n >= 6 { if strings.HasPrefix(value, "'''") { if !strings.HasSuffix(value, "'''") { - return value, fmt.Errorf("unable to unescape string") + return value, errors.New("unable to unescape string") } value = "\"" + value[3:n-3] + "\"" } else if strings.HasPrefix(value, `"""`) { if !strings.HasSuffix(value, `"""`) { - return value, fmt.Errorf("unable to unescape string") + return value, errors.New("unable to unescape string") } value = "\"" + value[3:n-3] + "\"" } @@ -90,10 +90,10 @@ func unescape(value string, isBytes bool) (string, error) { // unescapeChar takes a string input and returns the following info: // -// value - the escaped unicode rune at the front of the string. -// encode - the value should be unicode-encoded -// tail - the remainder of the input string. -// err - error value, if the character could not be unescaped. +// value - the escaped unicode rune at the front of the string. +// encode - the value should be unicode-encoded +// tail - the remainder of the input string. +// err - error value, if the character could not be unescaped. // // When encode is true the return value may still fit within a single byte, // but unicode encoding is attempted which is more expensive than when the @@ -113,7 +113,7 @@ func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, // 2. Last character is the start of an escape sequence. if len(s) <= 1 { - err = fmt.Errorf("unable to unescape string, found '\\' as last character") + err = errors.New("unable to unescape string, found '\\' as last character") return } @@ -157,32 +157,32 @@ func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, case 'u': n = 4 if isBytes { - err = fmt.Errorf("unable to unescape string") + err = errors.New("unable to unescape string") return } case 'U': n = 8 if isBytes { - err = fmt.Errorf("unable to unescape string") + err = errors.New("unable to unescape string") return } } var v rune if len(s) < n { - err = fmt.Errorf("unable to unescape string") + err = errors.New("unable to unescape string") return } for j := 0; j < n; j++ { x, ok := unhex(s[j]) if !ok { - err = fmt.Errorf("unable to unescape string") + err = errors.New("unable to unescape string") return } v = v<<4 | x } s = s[n:] - if !isBytes && v > utf8.MaxRune { - err = fmt.Errorf("unable to unescape string") + if !isBytes && !utf8.ValidRune(v) { + err = errors.New("invalid unicode code point") return } value = v @@ -190,20 +190,20 @@ func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, // 5. Octal escape sequences, must be three digits \[0-3][0-7][0-7] case '0', '1', '2', '3': if len(s) < 2 { - err = fmt.Errorf("unable to unescape octal sequence in string") + err = errors.New("unable to unescape octal sequence in string") return } v := rune(c - '0') for j := 0; j < 2; j++ { x := s[j] if x < '0' || x > '7' { - err = fmt.Errorf("unable to unescape octal sequence in string") + err = errors.New("unable to unescape octal sequence in string") return } v = v*8 + rune(x-'0') } - if !isBytes && v > utf8.MaxRune { - err = fmt.Errorf("unable to unescape string") + if !isBytes && !utf8.ValidRune(v) { + err = errors.New("invalid unicode code point") return } value = v @@ -212,7 +212,7 @@ func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, // Unknown escape sequence. default: - err = fmt.Errorf("unable to unescape string") + err = errors.New("unable to unescape string") } tail = s diff --git a/e2e/vendor/github.com/google/cel-go/parser/unparser.go b/e2e/vendor/github.com/google/cel-go/parser/unparser.go index 91cf72944..ffd5b18e4 100644 --- a/e2e/vendor/github.com/google/cel-go/parser/unparser.go +++ b/e2e/vendor/github.com/google/cel-go/parser/unparser.go @@ -17,12 +17,14 @@ package parser import ( "errors" "fmt" + "regexp" "strconv" "strings" "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/operators" "github.com/google/cel-go/common/types" + "github.com/google/cel-go/common/types/ref" ) // Unparse takes an input expression and source position information and generates a human-readable @@ -65,6 +67,15 @@ func Unparse(expr ast.Expr, info *ast.SourceInfo, opts ...UnparserOption) (strin return un.str.String(), nil } +var identifierPartPattern *regexp.Regexp = regexp.MustCompile(`^[A-Za-z_][0-9A-Za-z_]*$`) + +func maybeQuoteField(field string) string { + if !identifierPartPattern.MatchString(field) || field == "in" { + return "`" + field + "`" + } + return field +} + // unparser visits an expression to reconstruct a human-readable string from an AST. type unparser struct { str strings.Builder @@ -263,8 +274,17 @@ func (un *unparser) visitCallUnary(expr ast.Expr) error { return un.visitMaybeNested(args[0], nested) } -func (un *unparser) visitConst(expr ast.Expr) error { - val := expr.AsLiteral() +func (un *unparser) visitConstVal(val ref.Val) error { + optional := false + if optVal, ok := val.(*types.Optional); ok { + if !optVal.HasValue() { + un.str.WriteString("optional.none()") + return nil + } + optional = true + un.str.WriteString("optional.of(") + val = optVal.GetValue() + } switch val := val.(type) { case types.Bool: un.str.WriteString(strconv.FormatBool(bool(val))) @@ -293,7 +313,21 @@ func (un *unparser) visitConst(expr ast.Expr) error { ui := strconv.FormatUint(uint64(val), 10) un.str.WriteString(ui) un.str.WriteString("u") + case *types.Optional: + if err := un.visitConstVal(val); err != nil { + return err + } default: + return errors.New("unsupported constant") + } + if optional { + un.str.WriteString(")") + } + return nil +} +func (un *unparser) visitConst(expr ast.Expr) error { + val := expr.AsLiteral() + if err := un.visitConstVal(val); err != nil { return fmt.Errorf("unsupported constant: %v", expr) } return nil @@ -352,7 +386,7 @@ func (un *unparser) visitSelectInternal(operand ast.Expr, testOnly bool, op stri return err } un.str.WriteString(op) - un.str.WriteString(field) + un.str.WriteString(maybeQuoteField(field)) if testOnly { un.str.WriteString(")") } @@ -370,7 +404,7 @@ func (un *unparser) visitStructMsg(expr ast.Expr) error { if field.IsOptional() { un.str.WriteString("?") } - un.str.WriteString(f) + un.str.WriteString(maybeQuoteField(f)) un.str.WriteString(": ") v := field.Value() err := un.visit(v) diff --git a/e2e/vendor/github.com/google/gofuzz/.travis.yml b/e2e/vendor/github.com/google/gofuzz/.travis.yml deleted file mode 100644 index 061d72ae0..000000000 --- a/e2e/vendor/github.com/google/gofuzz/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go - -go: - - 1.11.x - - 1.12.x - - 1.13.x - - master - -script: - - go test -cover diff --git a/e2e/vendor/github.com/google/gofuzz/CONTRIBUTING.md b/e2e/vendor/github.com/google/gofuzz/CONTRIBUTING.md deleted file mode 100644 index 97c1b34fd..000000000 --- a/e2e/vendor/github.com/google/gofuzz/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# How to contribute # - -We'd love to accept your patches and contributions to this project. There are -just a few small guidelines you need to follow. - - -## Contributor License Agreement ## - -Contributions to any Google project must be accompanied by a Contributor -License Agreement. This is not a copyright **assignment**, it simply gives -Google permission to use and redistribute your contributions as part of the -project. - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual - CLA][]. - - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA][]. - -You generally only need to submit a CLA once, so if you've already submitted -one (even if it was for a different project), you probably don't need to do it -again. - -[individual CLA]: https://developers.google.com/open-source/cla/individual -[corporate CLA]: https://developers.google.com/open-source/cla/corporate - - -## Submitting a patch ## - - 1. It's generally best to start by opening a new issue describing the bug or - feature you're intending to fix. Even if you think it's relatively minor, - it's helpful to know what people are working on. Mention in the initial - issue that you are planning to work on that bug or feature so that it can - be assigned to you. - - 1. Follow the normal process of [forking][] the project, and setup a new - branch to work in. It's important that each group of changes be done in - separate branches in order to ensure that a pull request only includes the - commits related to that bug or feature. - - 1. Go makes it very simple to ensure properly formatted code, so always run - `go fmt` on your code before committing it. You should also run - [golint][] over your code. As noted in the [golint readme][], it's not - strictly necessary that your code be completely "lint-free", but this will - help you find common style issues. - - 1. Any significant changes should almost always be accompanied by tests. The - project already has good test coverage, so look at some of the existing - tests if you're unsure how to go about it. [gocov][] and [gocov-html][] - are invaluable tools for seeing which parts of your code aren't being - exercised by your tests. - - 1. Do your best to have [well-formed commit messages][] for each change. - This provides consistency throughout the project, and ensures that commit - messages are able to be formatted properly by various git tools. - - 1. Finally, push the commits to your fork and submit a [pull request][]. - -[forking]: https://help.github.com/articles/fork-a-repo -[golint]: https://github.com/golang/lint -[golint readme]: https://github.com/golang/lint/blob/master/README -[gocov]: https://github.com/axw/gocov -[gocov-html]: https://github.com/matm/gocov-html -[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits -[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/e2e/vendor/github.com/google/gofuzz/doc.go b/e2e/vendor/github.com/google/gofuzz/doc.go deleted file mode 100644 index 9f9956d4a..000000000 --- a/e2e/vendor/github.com/google/gofuzz/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -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 fuzz is a library for populating go objects with random values. -package fuzz diff --git a/e2e/vendor/github.com/google/gofuzz/fuzz.go b/e2e/vendor/github.com/google/gofuzz/fuzz.go deleted file mode 100644 index 761520a8c..000000000 --- a/e2e/vendor/github.com/google/gofuzz/fuzz.go +++ /dev/null @@ -1,605 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -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 fuzz - -import ( - "fmt" - "math/rand" - "reflect" - "regexp" - "time" - - "github.com/google/gofuzz/bytesource" - "strings" -) - -// fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. -type fuzzFuncMap map[reflect.Type]reflect.Value - -// Fuzzer knows how to fill any object with random fields. -type Fuzzer struct { - fuzzFuncs fuzzFuncMap - defaultFuzzFuncs fuzzFuncMap - r *rand.Rand - nilChance float64 - minElements int - maxElements int - maxDepth int - skipFieldPatterns []*regexp.Regexp -} - -// New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, -// RandSource, NilChance, or NumElements in any order. -func New() *Fuzzer { - return NewWithSeed(time.Now().UnixNano()) -} - -func NewWithSeed(seed int64) *Fuzzer { - f := &Fuzzer{ - defaultFuzzFuncs: fuzzFuncMap{ - reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), - }, - - fuzzFuncs: fuzzFuncMap{}, - r: rand.New(rand.NewSource(seed)), - nilChance: .2, - minElements: 1, - maxElements: 10, - maxDepth: 100, - } - return f -} - -// NewFromGoFuzz is a helper function that enables using gofuzz (this -// project) with go-fuzz (https://github.com/dvyukov/go-fuzz) for continuous -// fuzzing. Essentially, it enables translating the fuzzing bytes from -// go-fuzz to any Go object using this library. -// -// This implementation promises a constant translation from a given slice of -// bytes to the fuzzed objects. This promise will remain over future -// versions of Go and of this library. -// -// Note: the returned Fuzzer should not be shared between multiple goroutines, -// as its deterministic output will no longer be available. -// -// Example: use go-fuzz to test the function `MyFunc(int)` in the package -// `mypackage`. Add the file: "mypacakge_fuzz.go" with the content: -// -// // +build gofuzz -// package mypacakge -// import fuzz "github.com/google/gofuzz" -// func Fuzz(data []byte) int { -// var i int -// fuzz.NewFromGoFuzz(data).Fuzz(&i) -// MyFunc(i) -// return 0 -// } -func NewFromGoFuzz(data []byte) *Fuzzer { - return New().RandSource(bytesource.New(data)) -} - -// Funcs adds each entry in fuzzFuncs as a custom fuzzing function. -// -// Each entry in fuzzFuncs must be a function taking two parameters. -// The first parameter must be a pointer or map. It is the variable that -// function will fill with random data. The second parameter must be a -// fuzz.Continue, which will provide a source of randomness and a way -// to automatically continue fuzzing smaller pieces of the first parameter. -// -// These functions are called sensibly, e.g., if you wanted custom string -// fuzzing, the function `func(s *string, c fuzz.Continue)` would get -// called and passed the address of strings. Maps and pointers will always -// be made/new'd for you, ignoring the NilChange option. For slices, it -// doesn't make much sense to pre-create them--Fuzzer doesn't know how -// long you want your slice--so take a pointer to a slice, and make it -// yourself. (If you don't want your map/pointer type pre-made, take a -// pointer to it, and make it yourself.) See the examples for a range of -// custom functions. -func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { - for i := range fuzzFuncs { - v := reflect.ValueOf(fuzzFuncs[i]) - if v.Kind() != reflect.Func { - panic("Need only funcs!") - } - t := v.Type() - if t.NumIn() != 2 || t.NumOut() != 0 { - panic("Need 2 in and 0 out params!") - } - argT := t.In(0) - switch argT.Kind() { - case reflect.Ptr, reflect.Map: - default: - panic("fuzzFunc must take pointer or map type") - } - if t.In(1) != reflect.TypeOf(Continue{}) { - panic("fuzzFunc's second parameter must be type fuzz.Continue") - } - f.fuzzFuncs[argT] = v - } - return f -} - -// RandSource causes f to get values from the given source of randomness. -// Use if you want deterministic fuzzing. -func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { - f.r = rand.New(s) - return f -} - -// NilChance sets the probability of creating a nil pointer, map, or slice to -// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. -func (f *Fuzzer) NilChance(p float64) *Fuzzer { - if p < 0 || p > 1 { - panic("p should be between 0 and 1, inclusive.") - } - f.nilChance = p - return f -} - -// NumElements sets the minimum and maximum number of elements that will be -// added to a non-nil map or slice. -func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { - if atLeast > atMost { - panic("atLeast must be <= atMost") - } - if atLeast < 0 { - panic("atLeast must be >= 0") - } - f.minElements = atLeast - f.maxElements = atMost - return f -} - -func (f *Fuzzer) genElementCount() int { - if f.minElements == f.maxElements { - return f.minElements - } - return f.minElements + f.r.Intn(f.maxElements-f.minElements+1) -} - -func (f *Fuzzer) genShouldFill() bool { - return f.r.Float64() >= f.nilChance -} - -// MaxDepth sets the maximum number of recursive fuzz calls that will be made -// before stopping. This includes struct members, pointers, and map and slice -// elements. -func (f *Fuzzer) MaxDepth(d int) *Fuzzer { - f.maxDepth = d - return f -} - -// Skip fields which match the supplied pattern. Call this multiple times if needed -// This is useful to skip XXX_ fields generated by protobuf -func (f *Fuzzer) SkipFieldsWithPattern(pattern *regexp.Regexp) *Fuzzer { - f.skipFieldPatterns = append(f.skipFieldPatterns, pattern) - return f -} - -// Fuzz recursively fills all of obj's fields with something random. First -// this tries to find a custom fuzz function (see Funcs). If there is no -// custom function this tests whether the object implements fuzz.Interface and, -// if so, calls Fuzz on it to fuzz itself. If that fails, this will see if -// there is a default fuzz function provided by this package. If all of that -// fails, this will generate random values for all primitive fields and then -// recurse for all non-primitives. -// -// This is safe for cyclic or tree-like structs, up to a limit. Use the -// MaxDepth method to adjust how deep you need it to recurse. -// -// obj must be a pointer. Only exported (public) fields can be set (thanks, -// golang :/ ) Intended for tests, so will panic on bad input or unimplemented -// fields. -func (f *Fuzzer) Fuzz(obj interface{}) { - v := reflect.ValueOf(obj) - if v.Kind() != reflect.Ptr { - panic("needed ptr!") - } - v = v.Elem() - f.fuzzWithContext(v, 0) -} - -// FuzzNoCustom is just like Fuzz, except that any custom fuzz function for -// obj's type will not be called and obj will not be tested for fuzz.Interface -// conformance. This applies only to obj and not other instances of obj's -// type. -// Not safe for cyclic or tree-like structs! -// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) -// Intended for tests, so will panic on bad input or unimplemented fields. -func (f *Fuzzer) FuzzNoCustom(obj interface{}) { - v := reflect.ValueOf(obj) - if v.Kind() != reflect.Ptr { - panic("needed ptr!") - } - v = v.Elem() - f.fuzzWithContext(v, flagNoCustomFuzz) -} - -const ( - // Do not try to find a custom fuzz function. Does not apply recursively. - flagNoCustomFuzz uint64 = 1 << iota -) - -func (f *Fuzzer) fuzzWithContext(v reflect.Value, flags uint64) { - fc := &fuzzerContext{fuzzer: f} - fc.doFuzz(v, flags) -} - -// fuzzerContext carries context about a single fuzzing run, which lets Fuzzer -// be thread-safe. -type fuzzerContext struct { - fuzzer *Fuzzer - curDepth int -} - -func (fc *fuzzerContext) doFuzz(v reflect.Value, flags uint64) { - if fc.curDepth >= fc.fuzzer.maxDepth { - return - } - fc.curDepth++ - defer func() { fc.curDepth-- }() - - if !v.CanSet() { - return - } - - if flags&flagNoCustomFuzz == 0 { - // Check for both pointer and non-pointer custom functions. - if v.CanAddr() && fc.tryCustom(v.Addr()) { - return - } - if fc.tryCustom(v) { - return - } - } - - if fn, ok := fillFuncMap[v.Kind()]; ok { - fn(v, fc.fuzzer.r) - return - } - - switch v.Kind() { - case reflect.Map: - if fc.fuzzer.genShouldFill() { - v.Set(reflect.MakeMap(v.Type())) - n := fc.fuzzer.genElementCount() - for i := 0; i < n; i++ { - key := reflect.New(v.Type().Key()).Elem() - fc.doFuzz(key, 0) - val := reflect.New(v.Type().Elem()).Elem() - fc.doFuzz(val, 0) - v.SetMapIndex(key, val) - } - return - } - v.Set(reflect.Zero(v.Type())) - case reflect.Ptr: - if fc.fuzzer.genShouldFill() { - v.Set(reflect.New(v.Type().Elem())) - fc.doFuzz(v.Elem(), 0) - return - } - v.Set(reflect.Zero(v.Type())) - case reflect.Slice: - if fc.fuzzer.genShouldFill() { - n := fc.fuzzer.genElementCount() - v.Set(reflect.MakeSlice(v.Type(), n, n)) - for i := 0; i < n; i++ { - fc.doFuzz(v.Index(i), 0) - } - return - } - v.Set(reflect.Zero(v.Type())) - case reflect.Array: - if fc.fuzzer.genShouldFill() { - n := v.Len() - for i := 0; i < n; i++ { - fc.doFuzz(v.Index(i), 0) - } - return - } - v.Set(reflect.Zero(v.Type())) - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - skipField := false - fieldName := v.Type().Field(i).Name - for _, pattern := range fc.fuzzer.skipFieldPatterns { - if pattern.MatchString(fieldName) { - skipField = true - break - } - } - if !skipField { - fc.doFuzz(v.Field(i), 0) - } - } - case reflect.Chan: - fallthrough - case reflect.Func: - fallthrough - case reflect.Interface: - fallthrough - default: - panic(fmt.Sprintf("Can't handle %#v", v.Interface())) - } -} - -// tryCustom searches for custom handlers, and returns true iff it finds a match -// and successfully randomizes v. -func (fc *fuzzerContext) tryCustom(v reflect.Value) bool { - // First: see if we have a fuzz function for it. - doCustom, ok := fc.fuzzer.fuzzFuncs[v.Type()] - if !ok { - // Second: see if it can fuzz itself. - if v.CanInterface() { - intf := v.Interface() - if fuzzable, ok := intf.(Interface); ok { - fuzzable.Fuzz(Continue{fc: fc, Rand: fc.fuzzer.r}) - return true - } - } - // Finally: see if there is a default fuzz function. - doCustom, ok = fc.fuzzer.defaultFuzzFuncs[v.Type()] - if !ok { - return false - } - } - - switch v.Kind() { - case reflect.Ptr: - if v.IsNil() { - if !v.CanSet() { - return false - } - v.Set(reflect.New(v.Type().Elem())) - } - case reflect.Map: - if v.IsNil() { - if !v.CanSet() { - return false - } - v.Set(reflect.MakeMap(v.Type())) - } - default: - return false - } - - doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ - fc: fc, - Rand: fc.fuzzer.r, - })}) - return true -} - -// Interface represents an object that knows how to fuzz itself. Any time we -// find a type that implements this interface we will delegate the act of -// fuzzing itself. -type Interface interface { - Fuzz(c Continue) -} - -// Continue can be passed to custom fuzzing functions to allow them to use -// the correct source of randomness and to continue fuzzing their members. -type Continue struct { - fc *fuzzerContext - - // For convenience, Continue implements rand.Rand via embedding. - // Use this for generating any randomness if you want your fuzzing - // to be repeatable for a given seed. - *rand.Rand -} - -// Fuzz continues fuzzing obj. obj must be a pointer. -func (c Continue) Fuzz(obj interface{}) { - v := reflect.ValueOf(obj) - if v.Kind() != reflect.Ptr { - panic("needed ptr!") - } - v = v.Elem() - c.fc.doFuzz(v, 0) -} - -// FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for -// obj's type will not be called and obj will not be tested for fuzz.Interface -// conformance. This applies only to obj and not other instances of obj's -// type. -func (c Continue) FuzzNoCustom(obj interface{}) { - v := reflect.ValueOf(obj) - if v.Kind() != reflect.Ptr { - panic("needed ptr!") - } - v = v.Elem() - c.fc.doFuzz(v, flagNoCustomFuzz) -} - -// RandString makes a random string up to 20 characters long. The returned string -// may include a variety of (valid) UTF-8 encodings. -func (c Continue) RandString() string { - return randString(c.Rand) -} - -// RandUint64 makes random 64 bit numbers. -// Weirdly, rand doesn't have a function that gives you 64 random bits. -func (c Continue) RandUint64() uint64 { - return randUint64(c.Rand) -} - -// RandBool returns true or false randomly. -func (c Continue) RandBool() bool { - return randBool(c.Rand) -} - -func fuzzInt(v reflect.Value, r *rand.Rand) { - v.SetInt(int64(randUint64(r))) -} - -func fuzzUint(v reflect.Value, r *rand.Rand) { - v.SetUint(randUint64(r)) -} - -func fuzzTime(t *time.Time, c Continue) { - var sec, nsec int64 - // Allow for about 1000 years of random time values, which keeps things - // like JSON parsing reasonably happy. - sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) - c.Fuzz(&nsec) - *t = time.Unix(sec, nsec) -} - -var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ - reflect.Bool: func(v reflect.Value, r *rand.Rand) { - v.SetBool(randBool(r)) - }, - reflect.Int: fuzzInt, - reflect.Int8: fuzzInt, - reflect.Int16: fuzzInt, - reflect.Int32: fuzzInt, - reflect.Int64: fuzzInt, - reflect.Uint: fuzzUint, - reflect.Uint8: fuzzUint, - reflect.Uint16: fuzzUint, - reflect.Uint32: fuzzUint, - reflect.Uint64: fuzzUint, - reflect.Uintptr: fuzzUint, - reflect.Float32: func(v reflect.Value, r *rand.Rand) { - v.SetFloat(float64(r.Float32())) - }, - reflect.Float64: func(v reflect.Value, r *rand.Rand) { - v.SetFloat(r.Float64()) - }, - reflect.Complex64: func(v reflect.Value, r *rand.Rand) { - v.SetComplex(complex128(complex(r.Float32(), r.Float32()))) - }, - reflect.Complex128: func(v reflect.Value, r *rand.Rand) { - v.SetComplex(complex(r.Float64(), r.Float64())) - }, - reflect.String: func(v reflect.Value, r *rand.Rand) { - v.SetString(randString(r)) - }, - reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { - panic("unimplemented") - }, -} - -// randBool returns true or false randomly. -func randBool(r *rand.Rand) bool { - return r.Int31()&(1<<30) == 0 -} - -type int63nPicker interface { - Int63n(int64) int64 -} - -// UnicodeRange describes a sequential range of unicode characters. -// Last must be numerically greater than First. -type UnicodeRange struct { - First, Last rune -} - -// UnicodeRanges describes an arbitrary number of sequential ranges of unicode characters. -// To be useful, each range must have at least one character (First <= Last) and -// there must be at least one range. -type UnicodeRanges []UnicodeRange - -// choose returns a random unicode character from the given range, using the -// given randomness source. -func (ur UnicodeRange) choose(r int63nPicker) rune { - count := int64(ur.Last - ur.First + 1) - return ur.First + rune(r.Int63n(count)) -} - -// CustomStringFuzzFunc constructs a FuzzFunc which produces random strings. -// Each character is selected from the range ur. If there are no characters -// in the range (cr.Last < cr.First), this will panic. -func (ur UnicodeRange) CustomStringFuzzFunc() func(s *string, c Continue) { - ur.check() - return func(s *string, c Continue) { - *s = ur.randString(c.Rand) - } -} - -// check is a function that used to check whether the first of ur(UnicodeRange) -// is greater than the last one. -func (ur UnicodeRange) check() { - if ur.Last < ur.First { - panic("The last encoding must be greater than the first one.") - } -} - -// randString of UnicodeRange makes a random string up to 20 characters long. -// Each character is selected form ur(UnicodeRange). -func (ur UnicodeRange) randString(r *rand.Rand) string { - n := r.Intn(20) - sb := strings.Builder{} - sb.Grow(n) - for i := 0; i < n; i++ { - sb.WriteRune(ur.choose(r)) - } - return sb.String() -} - -// defaultUnicodeRanges sets a default unicode range when user do not set -// CustomStringFuzzFunc() but wants fuzz string. -var defaultUnicodeRanges = UnicodeRanges{ - {' ', '~'}, // ASCII characters - {'\u00a0', '\u02af'}, // Multi-byte encoded characters - {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) -} - -// CustomStringFuzzFunc constructs a FuzzFunc which produces random strings. -// Each character is selected from one of the ranges of ur(UnicodeRanges). -// Each range has an equal probability of being chosen. If there are no ranges, -// or a selected range has no characters (.Last < .First), this will panic. -// Do not modify any of the ranges in ur after calling this function. -func (ur UnicodeRanges) CustomStringFuzzFunc() func(s *string, c Continue) { - // Check unicode ranges slice is empty. - if len(ur) == 0 { - panic("UnicodeRanges is empty.") - } - // if not empty, each range should be checked. - for i := range ur { - ur[i].check() - } - return func(s *string, c Continue) { - *s = ur.randString(c.Rand) - } -} - -// randString of UnicodeRanges makes a random string up to 20 characters long. -// Each character is selected form one of the ranges of ur(UnicodeRanges), -// and each range has an equal probability of being chosen. -func (ur UnicodeRanges) randString(r *rand.Rand) string { - n := r.Intn(20) - sb := strings.Builder{} - sb.Grow(n) - for i := 0; i < n; i++ { - sb.WriteRune(ur[r.Intn(len(ur))].choose(r)) - } - return sb.String() -} - -// randString makes a random string up to 20 characters long. The returned string -// may include a variety of (valid) UTF-8 encodings. -func randString(r *rand.Rand) string { - return defaultUnicodeRanges.randString(r) -} - -// randUint64 makes random 64 bit numbers. -// Weirdly, rand doesn't have a function that gives you 64 random bits. -func randUint64(r *rand.Rand) uint64 { - return uint64(r.Uint32())<<32 | uint64(r.Uint32()) -} diff --git a/e2e/vendor/github.com/gorilla/websocket/README.md b/e2e/vendor/github.com/gorilla/websocket/README.md index 2517a2871..ff8bfab0b 100644 --- a/e2e/vendor/github.com/gorilla/websocket/README.md +++ b/e2e/vendor/github.com/gorilla/websocket/README.md @@ -7,19 +7,13 @@ Gorilla WebSocket is a [Go](http://golang.org/) implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. ---- - -⚠️ **[The Gorilla WebSocket Package is looking for a new maintainer](https://github.com/gorilla/websocket/issues/370)** - ---- - ### Documentation * [API Reference](https://pkg.go.dev/github.com/gorilla/websocket?tab=doc) -* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) -* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) -* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) -* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) +* [Chat example](https://github.com/gorilla/websocket/tree/main/examples/chat) +* [Command example](https://github.com/gorilla/websocket/tree/main/examples/command) +* [Client and server example](https://github.com/gorilla/websocket/tree/main/examples/echo) +* [File watch example](https://github.com/gorilla/websocket/tree/main/examples/filewatch) ### Status @@ -35,5 +29,4 @@ package API is stable. The Gorilla WebSocket package passes the server tests in the [Autobahn Test Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn -subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). - +subdirectory](https://github.com/gorilla/websocket/tree/main/examples/autobahn). diff --git a/e2e/vendor/github.com/gorilla/websocket/client.go b/e2e/vendor/github.com/gorilla/websocket/client.go index 2efd83555..00917ea34 100644 --- a/e2e/vendor/github.com/gorilla/websocket/client.go +++ b/e2e/vendor/github.com/gorilla/websocket/client.go @@ -9,8 +9,8 @@ import ( "context" "crypto/tls" "errors" + "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptrace" @@ -51,18 +51,34 @@ func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufS // // It is safe to call Dialer's methods concurrently. type Dialer struct { + // The following custom dial functions can be set to establish + // connections to either the backend server or the proxy (if it + // exists). The scheme of the dialed entity (either backend or + // proxy) determines which custom dial function is selected: + // either NetDialTLSContext for HTTPS or NetDialContext/NetDial + // for HTTP. Since the "Proxy" function can determine the scheme + // dynamically, it can make sense to set multiple custom dial + // functions simultaneously. + // // NetDial specifies the dial function for creating TCP connections. If - // NetDial is nil, net.Dial is used. + // NetDial is nil, net.Dialer DialContext is used. + // If "Proxy" field is also set, this function dials the proxy--not + // the backend server. NetDial func(network, addr string) (net.Conn, error) // NetDialContext specifies the dial function for creating TCP connections. If // NetDialContext is nil, NetDial is used. + // If "Proxy" field is also set, this function dials the proxy--not + // the backend server. NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error) // NetDialTLSContext specifies the dial function for creating TLS/TCP connections. If // NetDialTLSContext is nil, NetDialContext is used. // If NetDialTLSContext is set, Dial assumes the TLS handshake is done there and // TLSClientConfig is ignored. + // If "Proxy" field is also set, this function dials the proxy (and performs + // the TLS handshake with the proxy, ignoring TLSClientConfig). In this TLS proxy + // dialing case the TLSClientConfig could still be necessary for TLS to the backend server. NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error) // Proxy specifies a function to return a proxy for a given @@ -73,7 +89,7 @@ type Dialer struct { // TLSClientConfig specifies the TLS configuration to use with tls.Client. // If nil, the default configuration is used. - // If either NetDialTLS or NetDialTLSContext are set, Dial assumes the TLS handshake + // If NetDialTLSContext is set, Dial assumes the TLS handshake // is done there and TLSClientConfig is ignored. TLSClientConfig *tls.Config @@ -244,71 +260,16 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h defer cancel() } - // Get network dial function. - var netDial func(network, add string) (net.Conn, error) - - switch u.Scheme { - case "http": - if d.NetDialContext != nil { - netDial = func(network, addr string) (net.Conn, error) { - return d.NetDialContext(ctx, network, addr) - } - } else if d.NetDial != nil { - netDial = d.NetDial - } - case "https": - if d.NetDialTLSContext != nil { - netDial = func(network, addr string) (net.Conn, error) { - return d.NetDialTLSContext(ctx, network, addr) - } - } else if d.NetDialContext != nil { - netDial = func(network, addr string) (net.Conn, error) { - return d.NetDialContext(ctx, network, addr) - } - } else if d.NetDial != nil { - netDial = d.NetDial - } - default: - return nil, nil, errMalformedURL - } - - if netDial == nil { - netDialer := &net.Dialer{} - netDial = func(network, addr string) (net.Conn, error) { - return netDialer.DialContext(ctx, network, addr) - } - } - - // If needed, wrap the dial function to set the connection deadline. - if deadline, ok := ctx.Deadline(); ok { - forwardDial := netDial - netDial = func(network, addr string) (net.Conn, error) { - c, err := forwardDial(network, addr) - if err != nil { - return nil, err - } - err = c.SetDeadline(deadline) - if err != nil { - c.Close() - return nil, err - } - return c, nil - } - } - - // If needed, wrap the dial function to connect through a proxy. + var proxyURL *url.URL if d.Proxy != nil { - proxyURL, err := d.Proxy(req) + proxyURL, err = d.Proxy(req) if err != nil { return nil, nil, err } - if proxyURL != nil { - dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial)) - if err != nil { - return nil, nil, err - } - netDial = dialer.Dial - } + } + netDial, err := d.netDialFn(ctx, proxyURL, u) + if err != nil { + return nil, nil, err } hostPort, hostNoPort := hostPortNoPort(u) @@ -317,24 +278,30 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h trace.GetConn(hostPort) } - netConn, err := netDial("tcp", hostPort) + netConn, err := netDial(ctx, "tcp", hostPort) + if err != nil { + return nil, nil, err + } if trace != nil && trace.GotConn != nil { trace.GotConn(httptrace.GotConnInfo{ Conn: netConn, }) } - if err != nil { - return nil, nil, err - } + // Close the network connection when returning an error. The variable + // netConn is set to nil before the success return at the end of the + // function. defer func() { if netConn != nil { - netConn.Close() + // It's safe to ignore the error from Close() because this code is + // only executed when returning a more important error to the + // application. + _ = netConn.Close() } }() - if u.Scheme == "https" && d.NetDialTLSContext == nil { - // If NetDialTLSContext is set, assume that the TLS handshake has already been done + // Do TLS handshake over established connection if a proxy exists. + if proxyURL != nil && u.Scheme == "https" { cfg := cloneTLSConfig(d.TLSClientConfig) if cfg.ServerName == "" { @@ -370,6 +337,17 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h resp, err := http.ReadResponse(conn.br, req) if err != nil { + if d.TLSClientConfig != nil { + for _, proto := range d.TLSClientConfig.NextProtos { + if proto != "http/1.1" { + return nil, nil, fmt.Errorf( + "websocket: protocol %q was given but is not supported;"+ + "sharing tls.Config with net/http Transport can cause this error: %w", + proto, err, + ) + } + } + } return nil, nil, err } @@ -388,7 +366,7 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h // debugging. buf := make([]byte, 1024) n, _ := io.ReadFull(resp.Body, buf) - resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) + resp.Body = io.NopCloser(bytes.NewReader(buf[:n])) return nil, resp, ErrBadHandshake } @@ -406,17 +384,134 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h break } - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) + resp.Body = io.NopCloser(bytes.NewReader([]byte{})) conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") - netConn.SetDeadline(time.Time{}) - netConn = nil // to avoid close in defer. + if err := netConn.SetDeadline(time.Time{}); err != nil { + return nil, resp, err + } + + // Success! Set netConn to nil to stop the deferred function above from + // closing the network connection. + netConn = nil + return conn, resp, nil } +// Returns the dial function to establish the connection to either the backend +// server or the proxy (if it exists). If the dialed entity is HTTPS, then the +// returned dial function *also* performs the TLS handshake to the dialed entity. +// NOTE: If a proxy exists, it is possible for a second TLS handshake to be +// necessary over the established connection. +func (d *Dialer) netDialFn(ctx context.Context, proxyURL *url.URL, backendURL *url.URL) (netDialerFunc, error) { + var netDial netDialerFunc + if proxyURL != nil { + netDial = d.netDialFromURL(proxyURL) + } else { + netDial = d.netDialFromURL(backendURL) + } + // If needed, wrap the dial function to set the connection deadline. + if deadline, ok := ctx.Deadline(); ok { + netDial = netDialWithDeadline(netDial, deadline) + } + // Proxy dialing is wrapped to implement CONNECT method and possibly proxy auth. + if proxyURL != nil { + return proxyFromURL(proxyURL, netDial) + } + return netDial, nil +} + +// Returns function to create the connection depending on the Dialer's +// custom dialing functions and the passed URL of entity connecting to. +func (d *Dialer) netDialFromURL(u *url.URL) netDialerFunc { + var netDial netDialerFunc + switch { + case d.NetDialContext != nil: + netDial = d.NetDialContext + case d.NetDial != nil: + netDial = func(ctx context.Context, net, addr string) (net.Conn, error) { + return d.NetDial(net, addr) + } + default: + netDial = (&net.Dialer{}).DialContext + } + // If dialed entity is HTTPS, then either use custom TLS dialing function (if exists) + // or wrap the previously computed "netDial" to use TLS config for handshake. + if u.Scheme == "https" { + if d.NetDialTLSContext != nil { + netDial = d.NetDialTLSContext + } else { + netDial = netDialWithTLSHandshake(netDial, d.TLSClientConfig, u) + } + } + return netDial +} + +// Returns wrapped "netDial" function, performing TLS handshake after connecting. +func netDialWithTLSHandshake(netDial netDialerFunc, tlsConfig *tls.Config, u *url.URL) netDialerFunc { + return func(ctx context.Context, unused, addr string) (net.Conn, error) { + hostPort, hostNoPort := hostPortNoPort(u) + trace := httptrace.ContextClientTrace(ctx) + if trace != nil && trace.GetConn != nil { + trace.GetConn(hostPort) + } + // Creates TCP connection to addr using passed "netDial" function. + conn, err := netDial(ctx, "tcp", addr) + if err != nil { + return nil, err + } + cfg := cloneTLSConfig(tlsConfig) + if cfg.ServerName == "" { + cfg.ServerName = hostNoPort + } + tlsConn := tls.Client(conn, cfg) + // Do the TLS handshake using TLSConfig over the wrapped connection. + if trace != nil && trace.TLSHandshakeStart != nil { + trace.TLSHandshakeStart() + } + err = doHandshake(ctx, tlsConn, cfg) + if trace != nil && trace.TLSHandshakeDone != nil { + trace.TLSHandshakeDone(tlsConn.ConnectionState(), err) + } + if err != nil { + tlsConn.Close() + return nil, err + } + return tlsConn, nil + } +} + +// Returns wrapped "netDial" function, setting passed deadline. +func netDialWithDeadline(netDial netDialerFunc, deadline time.Time) netDialerFunc { + return func(ctx context.Context, network, addr string) (net.Conn, error) { + c, err := netDial(ctx, network, addr) + if err != nil { + return nil, err + } + err = c.SetDeadline(deadline) + if err != nil { + c.Close() + return nil, err + } + return c, nil + } +} + func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return cfg.Clone() } + +func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { + if err := tlsConn.HandshakeContext(ctx); err != nil { + return err + } + if !cfg.InsecureSkipVerify { + if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { + return err + } + } + return nil +} diff --git a/e2e/vendor/github.com/gorilla/websocket/compression.go b/e2e/vendor/github.com/gorilla/websocket/compression.go index 813ffb1e8..fe1079edb 100644 --- a/e2e/vendor/github.com/gorilla/websocket/compression.go +++ b/e2e/vendor/github.com/gorilla/websocket/compression.go @@ -33,7 +33,11 @@ func decompressNoContextTakeover(r io.Reader) io.ReadCloser { "\x01\x00\x00\xff\xff" fr, _ := flateReaderPool.Get().(io.ReadCloser) - fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) + mr := io.MultiReader(r, strings.NewReader(tail)) + if err := fr.(flate.Resetter).Reset(mr, nil); err != nil { + // Reset never fails, but handle error in case that changes. + fr = flate.NewReader(mr) + } return &flateReadWrapper{fr} } diff --git a/e2e/vendor/github.com/gorilla/websocket/conn.go b/e2e/vendor/github.com/gorilla/websocket/conn.go index 331eebc85..9562ffd49 100644 --- a/e2e/vendor/github.com/gorilla/websocket/conn.go +++ b/e2e/vendor/github.com/gorilla/websocket/conn.go @@ -6,11 +6,10 @@ package websocket import ( "bufio" + "crypto/rand" "encoding/binary" "errors" "io" - "io/ioutil" - "math/rand" "net" "strconv" "strings" @@ -181,16 +180,16 @@ var ( errInvalidControlFrame = errors.New("websocket: invalid control frame") ) -func newMaskKey() [4]byte { - n := rand.Uint32() - return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} -} +// maskRand is an io.Reader for generating mask bytes. The reader is initialized +// to crypto/rand Reader. Tests swap the reader to a math/rand reader for +// reproducible results. +var maskRand = rand.Reader -func hideTempErr(err error) error { - if e, ok := err.(net.Error); ok && e.Temporary() { - err = &netError{msg: e.Error(), timeout: e.Timeout()} - } - return err +// newMaskKey returns a new 32 bit value for masking client frames. +func newMaskKey() [4]byte { + var k [4]byte + _, _ = io.ReadFull(maskRand, k[:]) + return k } func isControl(frameType int) bool { @@ -358,7 +357,6 @@ func (c *Conn) RemoteAddr() net.Addr { // Write methods func (c *Conn) writeFatal(err error) error { - err = hideTempErr(err) c.writeErrMu.Lock() if c.writeErr == nil { c.writeErr = err @@ -372,7 +370,9 @@ func (c *Conn) read(n int) ([]byte, error) { if err == io.EOF { err = errUnexpectedEOF } - c.br.Discard(len(p)) + // Discard is guaranteed to succeed because the number of bytes to discard + // is less than or equal to the number of bytes buffered. + _, _ = c.br.Discard(len(p)) return p, err } @@ -387,7 +387,9 @@ func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error return err } - c.conn.SetWriteDeadline(deadline) + if err := c.conn.SetWriteDeadline(deadline); err != nil { + return c.writeFatal(err) + } if len(buf1) == 0 { _, err = c.conn.Write(buf0) } else { @@ -397,7 +399,7 @@ func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error return c.writeFatal(err) } if frameType == CloseMessage { - c.writeFatal(ErrCloseSent) + _ = c.writeFatal(ErrCloseSent) } return nil } @@ -436,21 +438,27 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er maskBytes(key, 0, buf[6:]) } - d := 1000 * time.Hour - if !deadline.IsZero() { - d = deadline.Sub(time.Now()) + if deadline.IsZero() { + // No timeout for zero time. + <-c.mu + } else { + d := time.Until(deadline) if d < 0 { return errWriteTimeout } + select { + case <-c.mu: + default: + timer := time.NewTimer(d) + select { + case <-c.mu: + timer.Stop() + case <-timer.C: + return errWriteTimeout + } + } } - timer := time.NewTimer(d) - select { - case <-c.mu: - timer.Stop() - case <-timer.C: - return errWriteTimeout - } defer func() { c.mu <- struct{}{} }() c.writeErrMu.Lock() @@ -460,13 +468,14 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er return err } - c.conn.SetWriteDeadline(deadline) - _, err = c.conn.Write(buf) - if err != nil { + if err := c.conn.SetWriteDeadline(deadline); err != nil { + return c.writeFatal(err) + } + if _, err = c.conn.Write(buf); err != nil { return c.writeFatal(err) } if messageType == CloseMessage { - c.writeFatal(ErrCloseSent) + _ = c.writeFatal(ErrCloseSent) } return err } @@ -630,7 +639,7 @@ func (w *messageWriter) flushFrame(final bool, extra []byte) error { } if final { - w.endMessage(errWriteClosed) + _ = w.endMessage(errWriteClosed) return nil } @@ -795,7 +804,7 @@ func (c *Conn) advanceFrame() (int, error) { // 1. Skip remainder of previous frame. if c.readRemaining > 0 { - if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { + if _, err := io.CopyN(io.Discard, c.br, c.readRemaining); err != nil { return noFrame, err } } @@ -817,7 +826,7 @@ func (c *Conn) advanceFrame() (int, error) { rsv2 := p[0]&rsv2Bit != 0 rsv3 := p[0]&rsv3Bit != 0 mask := p[1]&maskBit != 0 - c.setReadRemaining(int64(p[1] & 0x7f)) + _ = c.setReadRemaining(int64(p[1] & 0x7f)) // will not fail because argument is >= 0 c.readDecompress = false if rsv1 { @@ -922,7 +931,8 @@ func (c *Conn) advanceFrame() (int, error) { } if c.readLimit > 0 && c.readLength > c.readLimit { - c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) + // Make a best effort to send a close message describing the problem. + _ = c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) return noFrame, ErrReadLimit } @@ -934,7 +944,7 @@ func (c *Conn) advanceFrame() (int, error) { var payload []byte if c.readRemaining > 0 { payload, err = c.read(int(c.readRemaining)) - c.setReadRemaining(0) + _ = c.setReadRemaining(0) // will not fail because argument is >= 0 if err != nil { return noFrame, err } @@ -981,7 +991,8 @@ func (c *Conn) handleProtocolError(message string) error { if len(data) > maxControlFramePayloadSize { data = data[:maxControlFramePayloadSize] } - c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)) + // Make a best effor to send a close message describing the problem. + _ = c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)) return errors.New("websocket: " + message) } @@ -1008,7 +1019,7 @@ func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { for c.readErr == nil { frameType, err := c.advanceFrame() if err != nil { - c.readErr = hideTempErr(err) + c.readErr = err break } @@ -1048,13 +1059,13 @@ func (r *messageReader) Read(b []byte) (int, error) { b = b[:c.readRemaining] } n, err := c.br.Read(b) - c.readErr = hideTempErr(err) + c.readErr = err if c.isServer { c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) } rem := c.readRemaining rem -= int64(n) - c.setReadRemaining(rem) + _ = c.setReadRemaining(rem) // rem is guaranteed to be >= 0 if c.readRemaining > 0 && c.readErr == io.EOF { c.readErr = errUnexpectedEOF } @@ -1069,7 +1080,7 @@ func (r *messageReader) Read(b []byte) (int, error) { frameType, err := c.advanceFrame() switch { case err != nil: - c.readErr = hideTempErr(err) + c.readErr = err case frameType == TextMessage || frameType == BinaryMessage: c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") } @@ -1094,7 +1105,7 @@ func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { if err != nil { return messageType, nil, err } - p, err = ioutil.ReadAll(r) + p, err = io.ReadAll(r) return messageType, p, err } @@ -1136,7 +1147,8 @@ func (c *Conn) SetCloseHandler(h func(code int, text string) error) { if h == nil { h = func(code int, text string) error { message := FormatCloseMessage(code, "") - c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) + // Make a best effor to send the close message. + _ = c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) return nil } } @@ -1158,13 +1170,9 @@ func (c *Conn) PingHandler() func(appData string) error { func (c *Conn) SetPingHandler(h func(appData string) error) { if h == nil { h = func(message string) error { - err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) - if err == ErrCloseSent { - return nil - } else if e, ok := err.(net.Error); ok && e.Temporary() { - return nil - } - return err + // Make a best effort to send the pong message. + _ = c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) + return nil } } c.handlePing = h @@ -1189,8 +1197,16 @@ func (c *Conn) SetPongHandler(h func(appData string) error) { c.handlePong = h } +// NetConn returns the underlying connection that is wrapped by c. +// Note that writing to or reading from this connection directly will corrupt the +// WebSocket connection. +func (c *Conn) NetConn() net.Conn { + return c.conn +} + // UnderlyingConn returns the internal net.Conn. This can be used to further // modifications to connection specific flags. +// Deprecated: Use the NetConn method. func (c *Conn) UnderlyingConn() net.Conn { return c.conn } diff --git a/e2e/vendor/github.com/gorilla/websocket/proxy.go b/e2e/vendor/github.com/gorilla/websocket/proxy.go index e0f466b72..d716a0588 100644 --- a/e2e/vendor/github.com/gorilla/websocket/proxy.go +++ b/e2e/vendor/github.com/gorilla/websocket/proxy.go @@ -6,34 +6,52 @@ package websocket import ( "bufio" + "bytes" + "context" "encoding/base64" "errors" "net" "net/http" "net/url" "strings" + + "golang.org/x/net/proxy" ) -type netDialerFunc func(network, addr string) (net.Conn, error) +type netDialerFunc func(ctx context.Context, network, addr string) (net.Conn, error) func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { - return fn(network, addr) + return fn(context.Background(), network, addr) } -func init() { - proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { - return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil - }) +func (fn netDialerFunc) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + return fn(ctx, network, addr) +} + +func proxyFromURL(proxyURL *url.URL, forwardDial netDialerFunc) (netDialerFunc, error) { + if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" { + return (&httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDial}).DialContext, nil + } + dialer, err := proxy.FromURL(proxyURL, forwardDial) + if err != nil { + return nil, err + } + if d, ok := dialer.(proxy.ContextDialer); ok { + return d.DialContext, nil + } + return func(ctx context.Context, net, addr string) (net.Conn, error) { + return dialer.Dial(net, addr) + }, nil } type httpProxyDialer struct { proxyURL *url.URL - forwardDial func(network, addr string) (net.Conn, error) + forwardDial netDialerFunc } -func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { +func (hpd *httpProxyDialer) DialContext(ctx context.Context, network string, addr string) (net.Conn, error) { hostPort, _ := hostPortNoPort(hpd.proxyURL) - conn, err := hpd.forwardDial(network, hostPort) + conn, err := hpd.forwardDial(ctx, network, hostPort) if err != nil { return nil, err } @@ -46,7 +64,6 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) connectHeader.Set("Proxy-Authorization", "Basic "+credential) } } - connectReq := &http.Request{ Method: http.MethodConnect, URL: &url.URL{Opaque: addr}, @@ -59,7 +76,7 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) return nil, err } - // Read response. It's OK to use and discard buffered reader here becaue + // Read response. It's OK to use and discard buffered reader here because // the remote server does not speak until spoken to. br := bufio.NewReader(conn) resp, err := http.ReadResponse(br, connectReq) @@ -68,8 +85,18 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) return nil, err } - if resp.StatusCode != 200 { - conn.Close() + // Close the response body to silence false positives from linters. Reset + // the buffered reader first to ensure that Close() does not read from + // conn. + // Note: Applications must call resp.Body.Close() on a response returned + // http.ReadResponse to inspect trailers or read another response from the + // buffered reader. The call to resp.Body.Close() does not release + // resources. + br.Reset(bytes.NewReader(nil)) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + _ = conn.Close() f := strings.SplitN(resp.Status, " ", 2) return nil, errors.New(f[1]) } diff --git a/e2e/vendor/github.com/gorilla/websocket/server.go b/e2e/vendor/github.com/gorilla/websocket/server.go index 24d53b38a..02ea01fdc 100644 --- a/e2e/vendor/github.com/gorilla/websocket/server.go +++ b/e2e/vendor/github.com/gorilla/websocket/server.go @@ -6,8 +6,7 @@ package websocket import ( "bufio" - "errors" - "io" + "net" "net/http" "net/url" "strings" @@ -101,8 +100,8 @@ func checkSameOrigin(r *http.Request) bool { func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { if u.Subprotocols != nil { clientProtocols := Subprotocols(r) - for _, serverProtocol := range u.Subprotocols { - for _, clientProtocol := range clientProtocols { + for _, clientProtocol := range clientProtocols { + for _, serverProtocol := range u.Subprotocols { if clientProtocol == serverProtocol { return clientProtocol } @@ -130,7 +129,8 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade } if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { - return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header") + w.Header().Set("Upgrade", "websocket") + return u.returnError(w, r, http.StatusUpgradeRequired, badHandshake+"'websocket' token not found in 'Upgrade' header") } if r.Method != http.MethodGet { @@ -154,8 +154,8 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade } challengeKey := r.Header.Get("Sec-Websocket-Key") - if challengeKey == "" { - return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank") + if !isValidChallengeKey(challengeKey) { + return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header must be Base64 encoded value of 16-byte in length") } subprotocol := u.selectSubprotocol(r, responseHeader) @@ -172,28 +172,37 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade } } - h, ok := w.(http.Hijacker) - if !ok { - return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") - } - var brw *bufio.ReadWriter - netConn, brw, err := h.Hijack() + netConn, brw, err := http.NewResponseController(w).Hijack() if err != nil { - return u.returnError(w, r, http.StatusInternalServerError, err.Error()) + return u.returnError(w, r, http.StatusInternalServerError, + "websocket: hijack: "+err.Error()) } - if brw.Reader.Buffered() > 0 { - netConn.Close() - return nil, errors.New("websocket: client sent data before handshake is complete") - } + // Close the network connection when returning an error. The variable + // netConn is set to nil before the success return at the end of the + // function. + defer func() { + if netConn != nil { + // It's safe to ignore the error from Close() because this code is + // only executed when returning a more important error to the + // application. + _ = netConn.Close() + } + }() var br *bufio.Reader - if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 { - // Reuse hijacked buffered reader as connection reader. + if u.ReadBufferSize == 0 && brw.Reader.Size() > 256 { + // Use hijacked buffered reader as the connection reader. br = brw.Reader + } else if brw.Reader.Buffered() > 0 { + // Wrap the network connection to read buffered data in brw.Reader + // before reading from the network connection. This should be rare + // because a client must not send message data before receiving the + // handshake response. + netConn = &brNetConn{br: brw.Reader, Conn: netConn} } - buf := bufioWriterBuffer(netConn, brw.Writer) + buf := brw.Writer.AvailableBuffer() var writeBuf []byte if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 { @@ -247,20 +256,30 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade } p = append(p, "\r\n"...) - // Clear deadlines set by HTTP server. - netConn.SetDeadline(time.Time{}) - if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) + if err := netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)); err != nil { + return nil, err + } + } else { + // Clear deadlines set by HTTP server. + if err := netConn.SetDeadline(time.Time{}); err != nil { + return nil, err + } } + if _, err = netConn.Write(p); err != nil { - netConn.Close() return nil, err } if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Time{}) + if err := netConn.SetWriteDeadline(time.Time{}); err != nil { + return nil, err + } } + // Success! Set netConn to nil to stop the deferred function above from + // closing the network connection. + netConn = nil + return c, nil } @@ -327,39 +346,28 @@ func IsWebSocketUpgrade(r *http.Request) bool { tokenListContainsValue(r.Header, "Upgrade", "websocket") } -// bufioReaderSize size returns the size of a bufio.Reader. -func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int { - // This code assumes that peek on a reset reader returns - // bufio.Reader.buf[:0]. - // TODO: Use bufio.Reader.Size() after Go 1.10 - br.Reset(originalReader) - if p, err := br.Peek(0); err == nil { - return cap(p) +type brNetConn struct { + br *bufio.Reader + net.Conn +} + +func (b *brNetConn) Read(p []byte) (n int, err error) { + if b.br != nil { + // Limit read to buferred data. + if n := b.br.Buffered(); len(p) > n { + p = p[:n] + } + n, err = b.br.Read(p) + if b.br.Buffered() == 0 { + b.br = nil + } + return n, err } - return 0 + return b.Conn.Read(p) } -// writeHook is an io.Writer that records the last slice passed to it vio -// io.Writer.Write. -type writeHook struct { - p []byte +// NetConn returns the underlying connection that is wrapped by b. +func (b *brNetConn) NetConn() net.Conn { + return b.Conn } -func (wh *writeHook) Write(p []byte) (int, error) { - wh.p = p - return len(p), nil -} - -// bufioWriterBuffer grabs the buffer from a bufio.Writer. -func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte { - // This code assumes that bufio.Writer.buf[:1] is passed to the - // bufio.Writer's underlying writer. - var wh writeHook - bw.Reset(&wh) - bw.WriteByte(0) - bw.Flush() - - bw.Reset(originalWriter) - - return wh.p[:cap(wh.p)] -} diff --git a/e2e/vendor/github.com/gorilla/websocket/tls_handshake.go b/e2e/vendor/github.com/gorilla/websocket/tls_handshake.go deleted file mode 100644 index a62b68ccb..000000000 --- a/e2e/vendor/github.com/gorilla/websocket/tls_handshake.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build go1.17 -// +build go1.17 - -package websocket - -import ( - "context" - "crypto/tls" -) - -func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { - if err := tlsConn.HandshakeContext(ctx); err != nil { - return err - } - if !cfg.InsecureSkipVerify { - if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { - return err - } - } - return nil -} diff --git a/e2e/vendor/github.com/gorilla/websocket/tls_handshake_116.go b/e2e/vendor/github.com/gorilla/websocket/tls_handshake_116.go deleted file mode 100644 index e1b2b44f6..000000000 --- a/e2e/vendor/github.com/gorilla/websocket/tls_handshake_116.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build !go1.17 -// +build !go1.17 - -package websocket - -import ( - "context" - "crypto/tls" -) - -func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { - if err := tlsConn.Handshake(); err != nil { - return err - } - if !cfg.InsecureSkipVerify { - if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { - return err - } - } - return nil -} diff --git a/e2e/vendor/github.com/gorilla/websocket/util.go b/e2e/vendor/github.com/gorilla/websocket/util.go index 7bf2f66c6..31a5dee64 100644 --- a/e2e/vendor/github.com/gorilla/websocket/util.go +++ b/e2e/vendor/github.com/gorilla/websocket/util.go @@ -281,3 +281,18 @@ headers: } return result } + +// isValidChallengeKey checks if the argument meets RFC6455 specification. +func isValidChallengeKey(s string) bool { + // From RFC6455: + // + // A |Sec-WebSocket-Key| header field with a base64-encoded (see + // Section 4 of [RFC4648]) value that, when decoded, is 16 bytes in + // length. + + if s == "" { + return false + } + decoded, err := base64.StdEncoding.DecodeString(s) + return err == nil && len(decoded) == 16 +} diff --git a/e2e/vendor/github.com/gorilla/websocket/x_net_proxy.go b/e2e/vendor/github.com/gorilla/websocket/x_net_proxy.go deleted file mode 100644 index 2e668f6b8..000000000 --- a/e2e/vendor/github.com/gorilla/websocket/x_net_proxy.go +++ /dev/null @@ -1,473 +0,0 @@ -// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. -//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy - -// Package proxy provides support for a variety of protocols to proxy network -// data. -// - -package websocket - -import ( - "errors" - "io" - "net" - "net/url" - "os" - "strconv" - "strings" - "sync" -) - -type proxy_direct struct{} - -// Direct is a direct proxy: one that makes network connections directly. -var proxy_Direct = proxy_direct{} - -func (proxy_direct) Dial(network, addr string) (net.Conn, error) { - return net.Dial(network, addr) -} - -// A PerHost directs connections to a default Dialer unless the host name -// requested matches one of a number of exceptions. -type proxy_PerHost struct { - def, bypass proxy_Dialer - - bypassNetworks []*net.IPNet - bypassIPs []net.IP - bypassZones []string - bypassHosts []string -} - -// NewPerHost returns a PerHost Dialer that directs connections to either -// defaultDialer or bypass, depending on whether the connection matches one of -// the configured rules. -func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost { - return &proxy_PerHost{ - def: defaultDialer, - bypass: bypass, - } -} - -// Dial connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - - return p.dialerForRequest(host).Dial(network, addr) -} - -func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer { - if ip := net.ParseIP(host); ip != nil { - for _, net := range p.bypassNetworks { - if net.Contains(ip) { - return p.bypass - } - } - for _, bypassIP := range p.bypassIPs { - if bypassIP.Equal(ip) { - return p.bypass - } - } - return p.def - } - - for _, zone := range p.bypassZones { - if strings.HasSuffix(host, zone) { - return p.bypass - } - if host == zone[1:] { - // For a zone ".example.com", we match "example.com" - // too. - return p.bypass - } - } - for _, bypassHost := range p.bypassHosts { - if bypassHost == host { - return p.bypass - } - } - return p.def -} - -// AddFromString parses a string that contains comma-separated values -// specifying hosts that should use the bypass proxy. Each value is either an -// IP address, a CIDR range, a zone (*.example.com) or a host name -// (localhost). A best effort is made to parse the string and errors are -// ignored. -func (p *proxy_PerHost) AddFromString(s string) { - hosts := strings.Split(s, ",") - for _, host := range hosts { - host = strings.TrimSpace(host) - if len(host) == 0 { - continue - } - if strings.Contains(host, "/") { - // We assume that it's a CIDR address like 127.0.0.0/8 - if _, net, err := net.ParseCIDR(host); err == nil { - p.AddNetwork(net) - } - continue - } - if ip := net.ParseIP(host); ip != nil { - p.AddIP(ip) - continue - } - if strings.HasPrefix(host, "*.") { - p.AddZone(host[1:]) - continue - } - p.AddHost(host) - } -} - -// AddIP specifies an IP address that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match an IP. -func (p *proxy_PerHost) AddIP(ip net.IP) { - p.bypassIPs = append(p.bypassIPs, ip) -} - -// AddNetwork specifies an IP range that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match. -func (p *proxy_PerHost) AddNetwork(net *net.IPNet) { - p.bypassNetworks = append(p.bypassNetworks, net) -} - -// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of -// "example.com" matches "example.com" and all of its subdomains. -func (p *proxy_PerHost) AddZone(zone string) { - if strings.HasSuffix(zone, ".") { - zone = zone[:len(zone)-1] - } - if !strings.HasPrefix(zone, ".") { - zone = "." + zone - } - p.bypassZones = append(p.bypassZones, zone) -} - -// AddHost specifies a host name that will use the bypass proxy. -func (p *proxy_PerHost) AddHost(host string) { - if strings.HasSuffix(host, ".") { - host = host[:len(host)-1] - } - p.bypassHosts = append(p.bypassHosts, host) -} - -// A Dialer is a means to establish a connection. -type proxy_Dialer interface { - // Dial connects to the given address via the proxy. - Dial(network, addr string) (c net.Conn, err error) -} - -// Auth contains authentication parameters that specific Dialers may require. -type proxy_Auth struct { - User, Password string -} - -// FromEnvironment returns the dialer specified by the proxy related variables in -// the environment. -func proxy_FromEnvironment() proxy_Dialer { - allProxy := proxy_allProxyEnv.Get() - if len(allProxy) == 0 { - return proxy_Direct - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return proxy_Direct - } - proxy, err := proxy_FromURL(proxyURL, proxy_Direct) - if err != nil { - return proxy_Direct - } - - noProxy := proxy_noProxyEnv.Get() - if len(noProxy) == 0 { - return proxy - } - - perHost := proxy_NewPerHost(proxy, proxy_Direct) - perHost.AddFromString(noProxy) - return perHost -} - -// proxySchemes is a map from URL schemes to a function that creates a Dialer -// from a URL with such a scheme. -var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error) - -// RegisterDialerType takes a URL scheme and a function to generate Dialers from -// a URL with that scheme and a forwarding Dialer. Registered schemes are used -// by FromURL. -func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) { - if proxy_proxySchemes == nil { - proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) - } - proxy_proxySchemes[scheme] = f -} - -// FromURL returns a Dialer given a URL specification and an underlying -// Dialer for it to make network requests. -func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) { - var auth *proxy_Auth - if u.User != nil { - auth = new(proxy_Auth) - auth.User = u.User.Username() - if p, ok := u.User.Password(); ok { - auth.Password = p - } - } - - switch u.Scheme { - case "socks5": - return proxy_SOCKS5("tcp", u.Host, auth, forward) - } - - // If the scheme doesn't match any of the built-in schemes, see if it - // was registered by another package. - if proxy_proxySchemes != nil { - if f, ok := proxy_proxySchemes[u.Scheme]; ok { - return f(u, forward) - } - } - - return nil, errors.New("proxy: unknown scheme: " + u.Scheme) -} - -var ( - proxy_allProxyEnv = &proxy_envOnce{ - names: []string{"ALL_PROXY", "all_proxy"}, - } - proxy_noProxyEnv = &proxy_envOnce{ - names: []string{"NO_PROXY", "no_proxy"}, - } -) - -// envOnce looks up an environment variable (optionally by multiple -// names) once. It mitigates expensive lookups on some platforms -// (e.g. Windows). -// (Borrowed from net/http/transport.go) -type proxy_envOnce struct { - names []string - once sync.Once - val string -} - -func (e *proxy_envOnce) Get() string { - e.once.Do(e.init) - return e.val -} - -func (e *proxy_envOnce) init() { - for _, n := range e.names { - e.val = os.Getenv(n) - if e.val != "" { - return - } - } -} - -// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address -// with an optional username and password. See RFC 1928 and RFC 1929. -func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) { - s := &proxy_socks5{ - network: network, - addr: addr, - forward: forward, - } - if auth != nil { - s.user = auth.User - s.password = auth.Password - } - - return s, nil -} - -type proxy_socks5 struct { - user, password string - network, addr string - forward proxy_Dialer -} - -const proxy_socks5Version = 5 - -const ( - proxy_socks5AuthNone = 0 - proxy_socks5AuthPassword = 2 -) - -const proxy_socks5Connect = 1 - -const ( - proxy_socks5IP4 = 1 - proxy_socks5Domain = 3 - proxy_socks5IP6 = 4 -) - -var proxy_socks5Errors = []string{ - "", - "general failure", - "connection forbidden", - "network unreachable", - "host unreachable", - "connection refused", - "TTL expired", - "command not supported", - "address type not supported", -} - -// Dial connects to the address addr on the given network via the SOCKS5 proxy. -func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) - } - - conn, err := s.forward.Dial(s.network, s.addr) - if err != nil { - return nil, err - } - if err := s.connect(conn, addr); err != nil { - conn.Close() - return nil, err - } - return conn, nil -} - -// connect takes an existing connection to a socks5 proxy server, -// and commands the server to extend that connection to target, -// which must be a canonical address with a host and port. -func (s *proxy_socks5) connect(conn net.Conn, target string) error { - host, portStr, err := net.SplitHostPort(target) - if err != nil { - return err - } - - port, err := strconv.Atoi(portStr) - if err != nil { - return errors.New("proxy: failed to parse port number: " + portStr) - } - if port < 1 || port > 0xffff { - return errors.New("proxy: port number out of range: " + portStr) - } - - // the size here is just an estimate - buf := make([]byte, 0, 6+len(host)) - - buf = append(buf, proxy_socks5Version) - if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { - buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword) - } else { - buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone) - } - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - if buf[0] != 5 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) - } - if buf[1] == 0xff { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") - } - - // See RFC 1929 - if buf[1] == proxy_socks5AuthPassword { - buf = buf[:0] - buf = append(buf, 1 /* password protocol version */) - buf = append(buf, uint8(len(s.user))) - buf = append(buf, s.user...) - buf = append(buf, uint8(len(s.password))) - buf = append(buf, s.password...) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if buf[1] != 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") - } - } - - buf = buf[:0] - buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */) - - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - buf = append(buf, proxy_socks5IP4) - ip = ip4 - } else { - buf = append(buf, proxy_socks5IP6) - } - buf = append(buf, ip...) - } else { - if len(host) > 255 { - return errors.New("proxy: destination host name too long: " + host) - } - buf = append(buf, proxy_socks5Domain) - buf = append(buf, byte(len(host))) - buf = append(buf, host...) - } - buf = append(buf, byte(port>>8), byte(port)) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:4]); err != nil { - return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - failure := "unknown error" - if int(buf[1]) < len(proxy_socks5Errors) { - failure = proxy_socks5Errors[buf[1]] - } - - if len(failure) > 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) - } - - bytesToDiscard := 0 - switch buf[3] { - case proxy_socks5IP4: - bytesToDiscard = net.IPv4len - case proxy_socks5IP6: - bytesToDiscard = net.IPv6len - case proxy_socks5Domain: - _, err := io.ReadFull(conn, buf[:1]) - if err != nil { - return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - bytesToDiscard = int(buf[0]) - default: - return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) - } - - if cap(buf) < bytesToDiscard { - buf = make([]byte, bytesToDiscard) - } else { - buf = buf[:bytesToDiscard] - } - if _, err := io.ReadFull(conn, buf); err != nil { - return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - // Also need to discard the port number - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - return nil -} diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel index 78d7c9f5c..a65d88eb8 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel @@ -73,7 +73,7 @@ go_test( "@org_golang_google_genproto_googleapis_api//httpbody", "@org_golang_google_genproto_googleapis_rpc//errdetails", "@org_golang_google_genproto_googleapis_rpc//status", - "@org_golang_google_grpc//:go_default_library", + "@org_golang_google_grpc//:grpc", "@org_golang_google_grpc//codes", "@org_golang_google_grpc//health/grpc_health_v1", "@org_golang_google_grpc//metadata", diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go index 5dd4e4478..2f2b34243 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -49,6 +49,7 @@ var malformedHTTPHeaders = map[string]struct{}{ type ( rpcMethodKey struct{} httpPathPatternKey struct{} + httpPatternKey struct{} AnnotateContextOption func(ctx context.Context) context.Context ) @@ -404,3 +405,13 @@ func HTTPPathPattern(ctx context.Context) (string, bool) { func withHTTPPathPattern(ctx context.Context, httpPathPattern string) context.Context { return context.WithValue(ctx, httpPathPatternKey{}, httpPathPattern) } + +// HTTPPattern returns the HTTP path pattern struct relating to the HTTP handler, if one exists. +func HTTPPattern(ctx context.Context) (Pattern, bool) { + v, ok := ctx.Value(httpPatternKey{}).(Pattern) + return v, ok +} + +func withHTTPPattern(ctx context.Context, httpPattern Pattern) context.Context { + return context.WithValue(ctx, httpPatternKey{}, httpPattern) +} diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go index d7b15fcfb..2e50082ad 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go @@ -94,7 +94,7 @@ func Int64(val string) (int64, error) { } // Int64Slice converts 'val' where individual integers are separated by -// 'sep' into a int64 slice. +// 'sep' into an int64 slice. func Int64Slice(val, sep string) ([]int64, error) { s := strings.Split(val, sep) values := make([]int64, len(s)) @@ -118,7 +118,7 @@ func Int32(val string) (int32, error) { } // Int32Slice converts 'val' where individual integers are separated by -// 'sep' into a int32 slice. +// 'sep' into an int32 slice. func Int32Slice(val, sep string) ([]int32, error) { s := strings.Split(val, sep) values := make([]int32, len(s)) @@ -190,7 +190,7 @@ func Bytes(val string) ([]byte, error) { } // BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe -// base64 without padding, are separated by 'sep' into a slice of bytes slices slice. +// base64 without padding, are separated by 'sep' into a slice of byte slices. func BytesSlice(val, sep string) ([][]byte, error) { s := strings.Split(val, sep) values := make([][]byte, len(s)) diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go index 568299869..41cd4f503 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go @@ -81,6 +81,21 @@ func HTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.R mux.errorHandler(ctx, mux, marshaler, w, r, err) } +// HTTPStreamError uses the mux-configured stream error handler to notify error to the client without closing the connection. +func HTTPStreamError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + st := mux.streamErrorHandler(ctx, err) + msg := errorChunk(st) + buf, err := marshaler.Marshal(msg) + if err != nil { + grpclog.Errorf("Failed to marshal an error: %v", err) + return + } + if _, err := w.Write(buf); err != nil { + grpclog.Errorf("Failed to notify error to client: %v", err) + return + } +} + // DefaultHTTPErrorHandler is the default error handler. // If "err" is a gRPC Status, the function replies with the status code mapped by HTTPStatusFromCode. // If "err" is a HTTPStatusError, the function replies with the status code provide by that struct. This is @@ -93,6 +108,7 @@ func HTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.R func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { // return Internal when Marshal failed const fallback = `{"code": 13, "message": "failed to marshal error message"}` + const fallbackRewriter = `{"code": 13, "message": "failed to rewrite error message"}` var customStatus *HTTPStatusError if errors.As(err, &customStatus) { @@ -100,19 +116,28 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh } s := status.Convert(err) - pb := s.Proto() w.Header().Del("Trailer") w.Header().Del("Transfer-Encoding") - contentType := marshaler.ContentType(pb) + respRw, err := mux.forwardResponseRewriter(ctx, s.Proto()) + if err != nil { + grpclog.Errorf("Failed to rewrite error message %q: %v", s, err) + w.WriteHeader(http.StatusInternalServerError) + if _, err := io.WriteString(w, fallbackRewriter); err != nil { + grpclog.Errorf("Failed to write response: %v", err) + } + return + } + + contentType := marshaler.ContentType(respRw) w.Header().Set("Content-Type", contentType) if s.Code() == codes.Unauthenticated { w.Header().Set("WWW-Authenticate", s.Message()) } - buf, merr := marshaler.Marshal(pb) + buf, merr := marshaler.Marshal(respRw) if merr != nil { grpclog.Errorf("Failed to marshal error message %q: %v", s, merr) w.WriteHeader(http.StatusInternalServerError) diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go index 9005d6a0b..2fcd7af3c 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go @@ -155,7 +155,7 @@ func buildPathsBlindly(name string, in interface{}) []string { return paths } -// fieldMaskPathItem stores a in-progress deconstruction of a path for a fieldmask +// fieldMaskPathItem stores an in-progress deconstruction of a path for a fieldmask type fieldMaskPathItem struct { // the list of prior fields leading up to node connected by dots path string diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go index de1eef1f4..0fa907656 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go @@ -3,6 +3,7 @@ package runtime import ( "context" "errors" + "fmt" "io" "net/http" "net/textproto" @@ -55,20 +56,33 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal return } + respRw, err := mux.forwardResponseRewriter(ctx, resp) + if err != nil { + grpclog.Errorf("Rewrite error: %v", err) + handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err, delimiter) + return + } + if !wroteHeader { - w.Header().Set("Content-Type", marshaler.ContentType(resp)) + var contentType string + if sct, ok := marshaler.(StreamContentType); ok { + contentType = sct.StreamContentType(respRw) + } else { + contentType = marshaler.ContentType(respRw) + } + w.Header().Set("Content-Type", contentType) } var buf []byte - httpBody, isHTTPBody := resp.(*httpbody.HttpBody) + httpBody, isHTTPBody := respRw.(*httpbody.HttpBody) switch { - case resp == nil: + case respRw == nil: buf, err = marshaler.Marshal(errorChunk(status.New(codes.Internal, "empty response"))) case isHTTPBody: buf = httpBody.GetData() default: - result := map[string]interface{}{"result": resp} - if rb, ok := resp.(responseBody); ok { + result := map[string]interface{}{"result": respRw} + if rb, ok := respRw.(responseBody); ok { result["result"] = rb.XXX_ResponseBody() } @@ -164,12 +178,17 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha HTTPError(ctx, mux, marshaler, w, req, err) return } + respRw, err := mux.forwardResponseRewriter(ctx, resp) + if err != nil { + grpclog.Errorf("Rewrite error: %v", err) + HTTPError(ctx, mux, marshaler, w, req, err) + return + } var buf []byte - var err error - if rb, ok := resp.(responseBody); ok { + if rb, ok := respRw.(responseBody); ok { buf, err = marshaler.Marshal(rb.XXX_ResponseBody()) } else { - buf, err = marshaler.Marshal(resp) + buf, err = marshaler.Marshal(respRw) } if err != nil { grpclog.Errorf("Marshal error: %v", err) @@ -181,7 +200,7 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha w.Header().Set("Content-Length", strconv.Itoa(len(buf))) } - if _, err = w.Write(buf); err != nil { + if _, err = w.Write(buf); err != nil && !errors.Is(err, http.ErrBodyNotAllowed) { grpclog.Errorf("Failed to write response: %v", err) } @@ -201,8 +220,7 @@ func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, re } for _, opt := range opts { if err := opt(ctx, w, resp); err != nil { - grpclog.Errorf("Error handling ForwardResponseOptions: %v", err) - return err + return fmt.Errorf("error handling ForwardResponseOptions: %w", err) } } return nil diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go index 2c0d25ff4..b1dfc37af 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go @@ -48,3 +48,11 @@ type Delimited interface { // Delimiter returns the record separator for the stream. Delimiter() []byte } + +// StreamContentType defines the streaming content type. +type StreamContentType interface { + // StreamContentType returns the content type for a stream. This shares the + // same behaviour as for `Marshaler.ContentType`, but is called, if present, + // in the case of a streamed response. + StreamContentType(v interface{}) string +} diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go index 0b051e6e8..07c28112c 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go @@ -86,8 +86,8 @@ func (m marshalerRegistry) add(mime string, marshaler Marshaler) error { // It allows for a mapping of case-sensitive Content-Type MIME type string to runtime.Marshaler interfaces. // // For example, you could allow the client to specify the use of the runtime.JSONPb marshaler -// with a "application/jsonpb" Content-Type and the use of the runtime.JSONBuiltin marshaler -// with a "application/json" Content-Type. +// with an "application/jsonpb" Content-Type and the use of the runtime.JSONBuiltin marshaler +// with an "application/json" Content-Type. // "*" can be used to match any Content-Type. // This can be attached to a ServerMux with the marshaler option. func makeMarshalerMIMERegistry() marshalerRegistry { diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go index ed9a7e438..60c2065dd 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -48,12 +48,19 @@ var encodedPathSplitter = regexp.MustCompile("(/|%2F)") // A HandlerFunc handles a specific pair of path pattern and HTTP method. type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) +// A Middleware handler wraps another HandlerFunc to do some pre- and/or post-processing of the request. This is used as an alternative to gRPC interceptors when using the direct-to-implementation +// registration methods. It is generally recommended to use gRPC client or server interceptors instead +// where possible. +type Middleware func(HandlerFunc) HandlerFunc + // ServeMux is a request multiplexer for grpc-gateway. // It matches http requests to patterns and invokes the corresponding handler. type ServeMux struct { // handlers maps HTTP method to a list of handlers. handlers map[string][]handler + middlewares []Middleware forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error + forwardResponseRewriter ForwardResponseRewriter marshalers marshalerRegistry incomingHeaderMatcher HeaderMatcherFunc outgoingHeaderMatcher HeaderMatcherFunc @@ -69,6 +76,24 @@ type ServeMux struct { // ServeMuxOption is an option that can be given to a ServeMux on construction. type ServeMuxOption func(*ServeMux) +// ForwardResponseRewriter is the signature of a function that is capable of rewriting messages +// before they are forwarded in a unary, stream, or error response. +type ForwardResponseRewriter func(ctx context.Context, response proto.Message) (any, error) + +// WithForwardResponseRewriter returns a ServeMuxOption that allows for implementers to insert logic +// that can rewrite the final response before it is forwarded. +// +// The response rewriter function is called during unary message forwarding, stream message +// forwarding and when errors are being forwarded. +// +// NOTE: Using this option will likely make what is generated by `protoc-gen-openapiv2` incorrect. +// Since this option involves making runtime changes to the response shape or type. +func WithForwardResponseRewriter(fwdResponseRewriter ForwardResponseRewriter) ServeMuxOption { + return func(sm *ServeMux) { + sm.forwardResponseRewriter = fwdResponseRewriter + } +} + // WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption. // // forwardResponseOption is an option that will be called on the relevant context.Context, @@ -89,6 +114,15 @@ func WithUnescapingMode(mode UnescapingMode) ServeMuxOption { } } +// WithMiddlewares sets server middleware for all handlers. This is useful as an alternative to gRPC +// interceptors when using the direct-to-implementation registration methods and cannot rely +// on gRPC interceptors. It's recommended to use gRPC interceptors instead if possible. +func WithMiddlewares(middlewares ...Middleware) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.middlewares = append(serveMux.middlewares, middlewares...) + } +} + // SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. // Configuring this will mean the generated OpenAPI output is no longer correct, and it should be // done with careful consideration. @@ -277,13 +311,14 @@ func WithHealthzEndpoint(healthCheckClient grpc_health_v1.HealthClient) ServeMux // NewServeMux returns a new ServeMux whose internal mapping is empty. func NewServeMux(opts ...ServeMuxOption) *ServeMux { serveMux := &ServeMux{ - handlers: make(map[string][]handler), - forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), - marshalers: makeMarshalerMIMERegistry(), - errorHandler: DefaultHTTPErrorHandler, - streamErrorHandler: DefaultStreamErrorHandler, - routingErrorHandler: DefaultRoutingErrorHandler, - unescapingMode: UnescapingModeDefault, + handlers: make(map[string][]handler), + forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), + forwardResponseRewriter: func(ctx context.Context, response proto.Message) (any, error) { return response, nil }, + marshalers: makeMarshalerMIMERegistry(), + errorHandler: DefaultHTTPErrorHandler, + streamErrorHandler: DefaultStreamErrorHandler, + routingErrorHandler: DefaultRoutingErrorHandler, + unescapingMode: UnescapingModeDefault, } for _, opt := range opts { @@ -305,6 +340,9 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux { // Handle associates "h" to the pair of HTTP method and path pattern. func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { + if len(s.middlewares) > 0 { + h = chainMiddlewares(s.middlewares)(h) + } s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...) } @@ -405,7 +443,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { } continue } - h.h(w, r, pathParams) + s.handleHandler(h, w, r, pathParams) return } @@ -458,7 +496,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.errorHandler(ctx, s, outboundMarshaler, w, r, sterr) return } - h.h(w, r, pathParams) + s.handleHandler(h, w, r, pathParams) return } _, outboundMarshaler := MarshalerForRequest(s, r) @@ -484,3 +522,16 @@ type handler struct { pat Pattern h HandlerFunc } + +func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) { + h.h(w, r.WithContext(withHTTPPattern(r.Context(), h.pat)), pathParams) +} + +func chainMiddlewares(mws []Middleware) Middleware { + return func(next HandlerFunc) HandlerFunc { + for i := len(mws); i > 0; i-- { + next = mws[i-1](next) + } + return next + } +} diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go index d549407f2..f710036b3 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go @@ -40,7 +40,7 @@ func Float32P(val string) (*float32, error) { } // Int64P parses the given string representation of an integer -// and returns a pointer to a int64 whose value is same as the parsed integer. +// and returns a pointer to an int64 whose value is same as the parsed integer. func Int64P(val string) (*int64, error) { i, err := Int64(val) if err != nil { @@ -50,7 +50,7 @@ func Int64P(val string) (*int64, error) { } // Int32P parses the given string representation of an integer -// and returns a pointer to a int32 whose value is same as the parsed integer. +// and returns a pointer to an int32 whose value is same as the parsed integer. func Int32P(val string) (*int32, error) { i, err := Int32(val) if err != nil { diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go index fe634174b..93fb09922 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go @@ -291,7 +291,11 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p if err != nil { return protoreflect.Value{}, err } - msg = timestamppb.New(t) + timestamp := timestamppb.New(t) + if ok := timestamp.IsValid(); !ok { + return protoreflect.Value{}, fmt.Errorf("%s before 0001-01-01", value) + } + msg = timestamp case "google.protobuf.Duration": d, err := time.ParseDuration(value) if err != nil { diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go index dfe7de486..38ca39cc5 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go @@ -1,6 +1,6 @@ package utilities -// An OpCode is a opcode of compiled path patterns. +// OpCode is an opcode of compiled path patterns. type OpCode int // These constants are the valid values of OpCode. diff --git a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go index d224ab776..66aa5f2dc 100644 --- a/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go +++ b/e2e/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go @@ -5,7 +5,7 @@ import ( "strings" ) -// flagInterface is an cut down interface to `flag` +// flagInterface is a cut down interface to `flag` type flagInterface interface { Var(value flag.Value, name string, usage string) } diff --git a/e2e/vendor/go.etcd.io/etcd/api/v3/version/version.go b/e2e/vendor/go.etcd.io/etcd/api/v3/version/version.go index 36719c192..03449b523 100644 --- a/e2e/vendor/go.etcd.io/etcd/api/v3/version/version.go +++ b/e2e/vendor/go.etcd.io/etcd/api/v3/version/version.go @@ -26,7 +26,7 @@ import ( var ( // MinClusterVersion is the min cluster version this etcd binary is compatible with. MinClusterVersion = "3.0.0" - Version = "3.5.16" + Version = "3.5.21" APIVersion = "unknown" // Git SHA Value will be set during build diff --git a/e2e/vendor/go.etcd.io/etcd/client/v3/README.md b/e2e/vendor/go.etcd.io/etcd/client/v3/README.md index 1e037d7eb..16c0fe888 100644 --- a/e2e/vendor/go.etcd.io/etcd/client/v3/README.md +++ b/e2e/vendor/go.etcd.io/etcd/client/v3/README.md @@ -11,13 +11,6 @@ go get go.etcd.io/etcd/client/v3 ``` -Warning: As etcd 3.5.0 was not yet released, the command above does not work. -After first pre-release of 3.5.0 [#12498](https://github.com/etcd-io/etcd/issues/12498), -etcd can be referenced using: -``` -go get go.etcd.io/etcd/client/v3@v3.5.0-pre -``` - ## Get started Create client using `clientv3.New`: diff --git a/e2e/vendor/go.etcd.io/etcd/client/v3/lease.go b/e2e/vendor/go.etcd.io/etcd/client/v3/lease.go index 4e7d1caf8..4877ee949 100644 --- a/e2e/vendor/go.etcd.io/etcd/client/v3/lease.go +++ b/e2e/vendor/go.etcd.io/etcd/client/v3/lease.go @@ -263,6 +263,12 @@ func (l *lessor) Leases(ctx context.Context) (*LeaseLeasesResponse, error) { return nil, ContextError(ctx, err) } +// To identify the context passed to `KeepAlive`, a key/value pair is +// attached to the context. The key is a `keepAliveCtxKey` object, and +// the value is the pointer to the context object itself, ensuring +// uniqueness as each context has a unique memory address. +type keepAliveCtxKey struct{} + func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAliveResponse, error) { ch := make(chan *LeaseKeepAliveResponse, LeaseResponseChSize) @@ -277,6 +283,10 @@ func (l *lessor) KeepAlive(ctx context.Context, id LeaseID) (<-chan *LeaseKeepAl default: } ka, ok := l.keepAlives[id] + + if ctx.Done() != nil { + ctx = context.WithValue(ctx, keepAliveCtxKey{}, &ctx) + } if !ok { // create fresh keep alive ka = &keepAlive{ @@ -347,7 +357,7 @@ func (l *lessor) keepAliveCtxCloser(ctx context.Context, id LeaseID, donec <-cha // close channel and remove context if still associated with keep alive for i, c := range ka.ctxs { - if c == ctx { + if c.Value(keepAliveCtxKey{}) == ctx.Value(keepAliveCtxKey{}) { close(ka.chs[i]) ka.ctxs = append(ka.ctxs[:i], ka.ctxs[i+1:]...) ka.chs = append(ka.chs[:i], ka.chs[i+1:]...) diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go index 6aae83bfd..b25641c55 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/client.go @@ -18,7 +18,7 @@ var DefaultClient = &http.Client{Transport: NewTransport(http.DefaultTransport)} // Get is a convenient replacement for http.Get that adds a span around the request. func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "GET", targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil) if err != nil { return nil, err } @@ -27,7 +27,7 @@ func Get(ctx context.Context, targetURL string) (resp *http.Response, err error) // Head is a convenient replacement for http.Head that adds a span around the request. func Head(ctx context.Context, targetURL string) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "HEAD", targetURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodHead, targetURL, nil) if err != nil { return nil, err } @@ -36,7 +36,7 @@ func Head(ctx context.Context, targetURL string) (resp *http.Response, err error // Post is a convenient replacement for http.Post that adds a span around the request. func Post(ctx context.Context, targetURL, contentType string, body io.Reader) (resp *http.Response, err error) { - req, err := http.NewRequestWithContext(ctx, "POST", targetURL, body) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, body) if err != nil { return nil, err } diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go index 214acaf58..a83a02627 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go @@ -18,20 +18,6 @@ const ( WriteErrorKey = attribute.Key("http.write_error") // if an error occurred while writing a reply, the string of the error (io.EOF is not recorded) ) -// Server HTTP metrics. -const ( - serverRequestSize = "http.server.request.size" // Incoming request bytes total - serverResponseSize = "http.server.response.size" // Incoming response bytes total - serverDuration = "http.server.duration" // Incoming end to end duration, milliseconds -) - -// Client HTTP metrics. -const ( - clientRequestSize = "http.client.request.size" // Outgoing request bytes total - clientResponseSize = "http.client.response.size" // Outgoing response bytes total - clientDuration = "http.client.duration" // Outgoing end to end duration, milliseconds -) - // Filter is a predicate used to determine whether a given http.request should // be traced. A Filter must return true if the request should be traced. type Filter func(*http.Request) bool diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go index f0a9bb9ef..a01bfafbe 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go @@ -8,6 +8,8 @@ import ( "net/http" "net/http/httptrace" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" @@ -33,8 +35,9 @@ type config struct { SpanNameFormatter func(string, *http.Request) string ClientTrace func(context.Context) *httptrace.ClientTrace - TracerProvider trace.TracerProvider - MeterProvider metric.MeterProvider + TracerProvider trace.TracerProvider + MeterProvider metric.MeterProvider + MetricAttributesFn func(*http.Request) []attribute.KeyValue } // Option interface used for setting optional config properties. @@ -194,3 +197,11 @@ func WithServerName(server string) Option { c.ServerName = server }) } + +// WithMetricAttributesFn returns an Option to set a function that maps an HTTP request to a slice of attribute.KeyValue. +// These attributes will be included in metrics for every request. +func WithMetricAttributesFn(metricAttributesFn func(r *http.Request) []attribute.KeyValue) Option { + return optionFunc(func(c *config) { + c.MetricAttributesFn = metricAttributesFn + }) +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index d01bdccf4..e555a475f 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -9,11 +9,9 @@ import ( "github.com/felixge/httpsnoop" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) @@ -24,7 +22,6 @@ type middleware struct { server string tracer trace.Tracer - meter metric.Meter propagators propagation.TextMapPropagator spanStartOptions []trace.SpanStartOption readEvent bool @@ -34,10 +31,7 @@ type middleware struct { publicEndpoint bool publicEndpointFn func(*http.Request) bool - traceSemconv semconv.HTTPServer - requestBytesCounter metric.Int64Counter - responseBytesCounter metric.Int64Counter - serverLatencyMeasure metric.Float64Histogram + semconv semconv.HTTPServer } func defaultHandlerFormatter(operation string, _ *http.Request) string { @@ -56,8 +50,6 @@ func NewHandler(handler http.Handler, operation string, opts ...Option) http.Han func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Handler { h := middleware{ operation: operation, - - traceSemconv: semconv.NewHTTPServer(), } defaultOpts := []Option{ @@ -67,7 +59,6 @@ func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Han c := newConfig(append(defaultOpts, opts...)...) h.configure(c) - h.createMeasures() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -78,7 +69,6 @@ func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Han func (h *middleware) configure(c *config) { h.tracer = c.Tracer - h.meter = c.Meter h.propagators = c.Propagators h.spanStartOptions = c.SpanStartOptions h.readEvent = c.ReadEvent @@ -88,36 +78,7 @@ func (h *middleware) configure(c *config) { h.publicEndpoint = c.PublicEndpoint h.publicEndpointFn = c.PublicEndpointFn h.server = c.ServerName -} - -func handleErr(err error) { - if err != nil { - otel.Handle(err) - } -} - -func (h *middleware) createMeasures() { - var err error - h.requestBytesCounter, err = h.meter.Int64Counter( - serverRequestSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP request messages."), - ) - handleErr(err) - - h.responseBytesCounter, err = h.meter.Int64Counter( - serverResponseSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP response messages."), - ) - handleErr(err) - - h.serverLatencyMeasure, err = h.meter.Float64Histogram( - serverDuration, - metric.WithUnit("ms"), - metric.WithDescription("Measures the duration of inbound HTTP requests."), - ) - handleErr(err) + h.semconv = semconv.NewHTTPServer(c.Meter) } // serveHTTP sets up tracing and calls the given next http.Handler with the span @@ -134,7 +95,7 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http ctx := h.propagators.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) opts := []trace.SpanStartOption{ - trace.WithAttributes(h.traceSemconv.RequestTraceAttrs(h.server, r)...), + trace.WithAttributes(h.semconv.RequestTraceAttrs(h.server, r)...), } opts = append(opts, h.spanStartOptions...) @@ -156,6 +117,11 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http } } + if startTime := StartTimeFromContext(ctx); !startTime.IsZero() { + opts = append(opts, trace.WithTimestamp(startTime)) + requestStartTime = startTime + } + ctx, span := tracer.Start(ctx, h.spanNameFormatter(h.operation, r), opts...) defer span.End() @@ -166,14 +132,12 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http } } - var bw bodyWrapper // if request body is nil or NoBody, we don't want to mutate the body as it // will affect the identity of it in an unforeseeable way because we assert // ReadCloser fulfills a certain interface and it is indeed nil or NoBody. + bw := request.NewBodyWrapper(r.Body, readRecordFunc) if r.Body != nil && r.Body != http.NoBody { - bw.ReadCloser = r.Body - bw.record = readRecordFunc - r.Body = &bw + r.Body = bw } writeRecordFunc := func(int64) {} @@ -183,13 +147,7 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http } } - rww := &respWriterWrapper{ - ResponseWriter: w, - record: writeRecordFunc, - ctx: ctx, - props: h.propagators, - statusCode: http.StatusOK, // default status code in case the Handler doesn't write anything - } + rww := request.NewRespWriterWrapper(w, writeRecordFunc) // Wrap w to use our ResponseWriter methods while also exposing // other interfaces that w may implement (http.CloseNotifier, @@ -217,35 +175,39 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http next.ServeHTTP(w, r.WithContext(ctx)) - span.SetStatus(semconv.ServerStatus(rww.statusCode)) - span.SetAttributes(h.traceSemconv.ResponseTraceAttrs(semconv.ResponseTelemetry{ - StatusCode: rww.statusCode, - ReadBytes: bw.read.Load(), - ReadError: bw.err, - WriteBytes: rww.written, - WriteError: rww.err, + statusCode := rww.StatusCode() + bytesWritten := rww.BytesWritten() + span.SetStatus(h.semconv.Status(statusCode)) + span.SetAttributes(h.semconv.ResponseTraceAttrs(semconv.ResponseTelemetry{ + StatusCode: statusCode, + ReadBytes: bw.BytesRead(), + ReadError: bw.Error(), + WriteBytes: bytesWritten, + WriteError: rww.Error(), })...) - // Add metrics - attributes := append(labeler.Get(), semconvutil.HTTPServerRequestMetrics(h.server, r)...) - if rww.statusCode > 0 { - attributes = append(attributes, semconv.HTTPStatusCode(rww.statusCode)) - } - o := metric.WithAttributeSet(attribute.NewSet(attributes...)) - addOpts := []metric.AddOption{o} // Allocate vararg slice once. - h.requestBytesCounter.Add(ctx, bw.read.Load(), addOpts...) - h.responseBytesCounter.Add(ctx, rww.written, addOpts...) - // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - h.serverLatencyMeasure.Record(ctx, elapsedTime, o) + h.semconv.RecordMetrics(ctx, semconv.ServerMetricData{ + ServerName: h.server, + ResponseSize: bytesWritten, + MetricAttributes: semconv.MetricAttributes{ + Req: r, + StatusCode: statusCode, + AdditionalAttributes: labeler.Get(), + }, + MetricData: semconv.MetricData{ + RequestSize: bw.BytesRead(), + ElapsedTime: elapsedTime, + }, + }) } // WithRouteTag annotates spans and metrics with the provided route name // with HTTP route attribute. func WithRouteTag(route string, h http.Handler) http.Handler { - attr := semconv.NewHTTPServer().Route(route) + attr := semconv.NewHTTPServer(nil).Route(route) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { span := trace.SpanFromContext(r.Context()) span.SetAttributes(attr) diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/body_wrapper.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/body_wrapper.go new file mode 100644 index 000000000..a945f5566 --- /dev/null +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/body_wrapper.go @@ -0,0 +1,75 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" + +import ( + "io" + "sync" +) + +var _ io.ReadCloser = &BodyWrapper{} + +// BodyWrapper wraps a http.Request.Body (an io.ReadCloser) to track the number +// of bytes read and the last error. +type BodyWrapper struct { + io.ReadCloser + OnRead func(n int64) // must not be nil + + mu sync.Mutex + read int64 + err error +} + +// NewBodyWrapper creates a new BodyWrapper. +// +// The onRead attribute is a callback that will be called every time the data +// is read, with the number of bytes being read. +func NewBodyWrapper(body io.ReadCloser, onRead func(int64)) *BodyWrapper { + return &BodyWrapper{ + ReadCloser: body, + OnRead: onRead, + } +} + +// Read reads the data from the io.ReadCloser, and stores the number of bytes +// read and the error. +func (w *BodyWrapper) Read(b []byte) (int, error) { + n, err := w.ReadCloser.Read(b) + n1 := int64(n) + + w.updateReadData(n1, err) + w.OnRead(n1) + return n, err +} + +func (w *BodyWrapper) updateReadData(n int64, err error) { + w.mu.Lock() + defer w.mu.Unlock() + + w.read += n + if err != nil { + w.err = err + } +} + +// Closes closes the io.ReadCloser. +func (w *BodyWrapper) Close() error { + return w.ReadCloser.Close() +} + +// BytesRead returns the number of bytes read up to this point. +func (w *BodyWrapper) BytesRead() int64 { + w.mu.Lock() + defer w.mu.Unlock() + + return w.read +} + +// Error returns the last error. +func (w *BodyWrapper) Error() error { + w.mu.Lock() + defer w.mu.Unlock() + + return w.err +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go new file mode 100644 index 000000000..fbc344cbd --- /dev/null +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request/resp_writer_wrapper.go @@ -0,0 +1,119 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" + +import ( + "net/http" + "sync" +) + +var _ http.ResponseWriter = &RespWriterWrapper{} + +// RespWriterWrapper wraps a http.ResponseWriter in order to track the number of +// bytes written, the last error, and to catch the first written statusCode. +// TODO: The wrapped http.ResponseWriter doesn't implement any of the optional +// types (http.Hijacker, http.Pusher, http.CloseNotifier, etc) +// that may be useful when using it in real life situations. +type RespWriterWrapper struct { + http.ResponseWriter + OnWrite func(n int64) // must not be nil + + mu sync.RWMutex + written int64 + statusCode int + err error + wroteHeader bool +} + +// NewRespWriterWrapper creates a new RespWriterWrapper. +// +// The onWrite attribute is a callback that will be called every time the data +// is written, with the number of bytes that were written. +func NewRespWriterWrapper(w http.ResponseWriter, onWrite func(int64)) *RespWriterWrapper { + return &RespWriterWrapper{ + ResponseWriter: w, + OnWrite: onWrite, + statusCode: http.StatusOK, // default status code in case the Handler doesn't write anything + } +} + +// Write writes the bytes array into the [ResponseWriter], and tracks the +// number of bytes written and last error. +func (w *RespWriterWrapper) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + + if !w.wroteHeader { + w.writeHeader(http.StatusOK) + } + + n, err := w.ResponseWriter.Write(p) + n1 := int64(n) + w.OnWrite(n1) + w.written += n1 + w.err = err + return n, err +} + +// WriteHeader persists initial statusCode for span attribution. +// All calls to WriteHeader will be propagated to the underlying ResponseWriter +// and will persist the statusCode from the first call. +// Blocking consecutive calls to WriteHeader alters expected behavior and will +// remove warning logs from net/http where developers will notice incorrect handler implementations. +func (w *RespWriterWrapper) WriteHeader(statusCode int) { + w.mu.Lock() + defer w.mu.Unlock() + + w.writeHeader(statusCode) +} + +// writeHeader persists the status code for span attribution, and propagates +// the call to the underlying ResponseWriter. +// It does not acquire a lock, and therefore assumes that is being handled by a +// parent method. +func (w *RespWriterWrapper) writeHeader(statusCode int) { + if !w.wroteHeader { + w.wroteHeader = true + w.statusCode = statusCode + } + w.ResponseWriter.WriteHeader(statusCode) +} + +// Flush implements [http.Flusher]. +func (w *RespWriterWrapper) Flush() { + w.mu.Lock() + defer w.mu.Unlock() + + if !w.wroteHeader { + w.writeHeader(http.StatusOK) + } + + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// BytesWritten returns the number of bytes written. +func (w *RespWriterWrapper) BytesWritten() int64 { + w.mu.RLock() + defer w.mu.RUnlock() + + return w.written +} + +// BytesWritten returns the HTTP status code that was sent. +func (w *RespWriterWrapper) StatusCode() int { + w.mu.RLock() + defer w.mu.RUnlock() + + return w.statusCode +} + +// Error returns the last error. +func (w *RespWriterWrapper) Error() error { + w.mu.RLock() + defer w.mu.RUnlock() + + return w.err +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go index 3ec0ad00c..3b036f8a3 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/env.go @@ -4,13 +4,16 @@ package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" import ( + "context" "fmt" "net/http" "os" "strings" + "sync" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/metric" ) type ResponseTelemetry struct { @@ -23,6 +26,11 @@ type ResponseTelemetry struct { type HTTPServer struct { duplicate bool + + // Old metrics + requestBytesCounter metric.Int64Counter + responseBytesCounter metric.Int64Counter + serverLatencyMeasure metric.Float64Histogram } // RequestTraceAttrs returns trace attributes for an HTTP request received by a @@ -43,9 +51,9 @@ type HTTPServer struct { // The req Host will be used to determine the server instead. func (s HTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { if s.duplicate { - return append(oldHTTPServer{}.RequestTraceAttrs(server, req), newHTTPServer{}.RequestTraceAttrs(server, req)...) + return append(OldHTTPServer{}.RequestTraceAttrs(server, req), CurrentHTTPServer{}.RequestTraceAttrs(server, req)...) } - return oldHTTPServer{}.RequestTraceAttrs(server, req) + return OldHTTPServer{}.RequestTraceAttrs(server, req) } // ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. @@ -53,25 +61,20 @@ func (s HTTPServer) RequestTraceAttrs(server string, req *http.Request) []attrib // If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. func (s HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { if s.duplicate { - return append(oldHTTPServer{}.ResponseTraceAttrs(resp), newHTTPServer{}.ResponseTraceAttrs(resp)...) + return append(OldHTTPServer{}.ResponseTraceAttrs(resp), CurrentHTTPServer{}.ResponseTraceAttrs(resp)...) } - return oldHTTPServer{}.ResponseTraceAttrs(resp) + return OldHTTPServer{}.ResponseTraceAttrs(resp) } // Route returns the attribute for the route. func (s HTTPServer) Route(route string) attribute.KeyValue { - return oldHTTPServer{}.Route(route) + return OldHTTPServer{}.Route(route) } -func NewHTTPServer() HTTPServer { - env := strings.ToLower(os.Getenv("OTEL_HTTP_CLIENT_COMPATIBILITY_MODE")) - return HTTPServer{duplicate: env == "http/dup"} -} - -// ServerStatus returns a span status code and message for an HTTP status code +// Status returns a span status code and message for an HTTP status code // value returned by a server. Status codes in the 400-499 range are not // returned as errors. -func ServerStatus(code int) (codes.Code, string) { +func (s HTTPServer) Status(code int) (codes.Code, string) { if code < 100 || code >= 600 { return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) } @@ -80,3 +83,155 @@ func ServerStatus(code int) (codes.Code, string) { } return codes.Unset, "" } + +type ServerMetricData struct { + ServerName string + ResponseSize int64 + + MetricData + MetricAttributes +} + +type MetricAttributes struct { + Req *http.Request + StatusCode int + AdditionalAttributes []attribute.KeyValue +} + +type MetricData struct { + RequestSize int64 + ElapsedTime float64 +} + +var metricAddOptionPool = &sync.Pool{ + New: func() interface{} { + return &[]metric.AddOption{} + }, +} + +func (s HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) { + if s.requestBytesCounter == nil || s.responseBytesCounter == nil || s.serverLatencyMeasure == nil { + // This will happen if an HTTPServer{} is used instead of NewHTTPServer. + return + } + + attributes := OldHTTPServer{}.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.AdditionalAttributes) + o := metric.WithAttributeSet(attribute.NewSet(attributes...)) + addOpts := metricAddOptionPool.Get().(*[]metric.AddOption) + *addOpts = append(*addOpts, o) + s.requestBytesCounter.Add(ctx, md.RequestSize, *addOpts...) + s.responseBytesCounter.Add(ctx, md.ResponseSize, *addOpts...) + s.serverLatencyMeasure.Record(ctx, md.ElapsedTime, o) + *addOpts = (*addOpts)[:0] + metricAddOptionPool.Put(addOpts) + + // TODO: Duplicate Metrics +} + +func NewHTTPServer(meter metric.Meter) HTTPServer { + env := strings.ToLower(os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")) + duplicate := env == "http/dup" + server := HTTPServer{ + duplicate: duplicate, + } + server.requestBytesCounter, server.responseBytesCounter, server.serverLatencyMeasure = OldHTTPServer{}.createMeasures(meter) + return server +} + +type HTTPClient struct { + duplicate bool + + // old metrics + requestBytesCounter metric.Int64Counter + responseBytesCounter metric.Int64Counter + latencyMeasure metric.Float64Histogram +} + +func NewHTTPClient(meter metric.Meter) HTTPClient { + env := strings.ToLower(os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")) + client := HTTPClient{ + duplicate: env == "http/dup", + } + client.requestBytesCounter, client.responseBytesCounter, client.latencyMeasure = OldHTTPClient{}.createMeasures(meter) + return client +} + +// RequestTraceAttrs returns attributes for an HTTP request made by a client. +func (c HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { + if c.duplicate { + return append(OldHTTPClient{}.RequestTraceAttrs(req), CurrentHTTPClient{}.RequestTraceAttrs(req)...) + } + return OldHTTPClient{}.RequestTraceAttrs(req) +} + +// ResponseTraceAttrs returns metric attributes for an HTTP request made by a client. +func (c HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { + if c.duplicate { + return append(OldHTTPClient{}.ResponseTraceAttrs(resp), CurrentHTTPClient{}.ResponseTraceAttrs(resp)...) + } + + return OldHTTPClient{}.ResponseTraceAttrs(resp) +} + +func (c HTTPClient) Status(code int) (codes.Code, string) { + if code < 100 || code >= 600 { + return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) + } + if code >= 400 { + return codes.Error, "" + } + return codes.Unset, "" +} + +func (c HTTPClient) ErrorType(err error) attribute.KeyValue { + if c.duplicate { + return CurrentHTTPClient{}.ErrorType(err) + } + + return attribute.KeyValue{} +} + +type MetricOpts struct { + measurement metric.MeasurementOption + addOptions metric.AddOption +} + +func (o MetricOpts) MeasurementOption() metric.MeasurementOption { + return o.measurement +} + +func (o MetricOpts) AddOptions() metric.AddOption { + return o.addOptions +} + +func (c HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts { + attributes := OldHTTPClient{}.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes) + // TODO: Duplicate Metrics + set := metric.WithAttributeSet(attribute.NewSet(attributes...)) + return MetricOpts{ + measurement: set, + addOptions: set, + } +} + +func (s HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts MetricOpts) { + if s.requestBytesCounter == nil || s.latencyMeasure == nil { + // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). + return + } + + s.requestBytesCounter.Add(ctx, md.RequestSize, opts.AddOptions()) + s.latencyMeasure.Record(ctx, md.ElapsedTime, opts.MeasurementOption()) + + // TODO: Duplicate Metrics +} + +func (s HTTPClient) RecordResponseSize(ctx context.Context, responseData int64, opts metric.AddOption) { + if s.responseBytesCounter == nil { + // This will happen if an HTTPClient{} is used instead of NewHTTPClient(). + return + } + + s.responseBytesCounter.Add(ctx, responseData, opts) + // TODO: Duplicate Metrics +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go new file mode 100644 index 000000000..dc9ec7bc3 --- /dev/null +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/httpconv.go @@ -0,0 +1,348 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" + +import ( + "fmt" + "net/http" + "reflect" + "strconv" + "strings" + + "go.opentelemetry.io/otel/attribute" + semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" +) + +type CurrentHTTPServer struct{} + +// TraceRequest returns trace attributes for an HTTP request received by a +// server. +// +// The server must be the primary server name if it is known. For example this +// would be the ServerName directive +// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache +// server, and the server_name directive +// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an +// nginx server. More generically, the primary server name would be the host +// header value that matches the default virtual host of an HTTP server. It +// should include the host identifier and if a port is used to route to the +// server that port identifier should be included as an appropriate port +// suffix. +// +// If the primary server name is not known, server should be an empty string. +// The req Host will be used to determine the server instead. +func (n CurrentHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { + count := 3 // ServerAddress, Method, Scheme + + var host string + var p int + if server == "" { + host, p = SplitHostPort(req.Host) + } else { + // Prioritize the primary server name. + host, p = SplitHostPort(server) + if p < 0 { + _, p = SplitHostPort(req.Host) + } + } + + hostPort := requiredHTTPPort(req.TLS != nil, p) + if hostPort > 0 { + count++ + } + + method, methodOriginal := n.method(req.Method) + if methodOriginal != (attribute.KeyValue{}) { + count++ + } + + scheme := n.scheme(req.TLS != nil) + + if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { + // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a + // file-path that would be interpreted with a sock family. + count++ + if peerPort > 0 { + count++ + } + } + + useragent := req.UserAgent() + if useragent != "" { + count++ + } + + clientIP := serverClientIP(req.Header.Get("X-Forwarded-For")) + if clientIP != "" { + count++ + } + + if req.URL != nil && req.URL.Path != "" { + count++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" && protoName != "http" { + count++ + } + if protoVersion != "" { + count++ + } + + attrs := make([]attribute.KeyValue, 0, count) + attrs = append(attrs, + semconvNew.ServerAddress(host), + method, + scheme, + ) + + if hostPort > 0 { + attrs = append(attrs, semconvNew.ServerPort(hostPort)) + } + if methodOriginal != (attribute.KeyValue{}) { + attrs = append(attrs, methodOriginal) + } + + if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" { + // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a + // file-path that would be interpreted with a sock family. + attrs = append(attrs, semconvNew.NetworkPeerAddress(peer)) + if peerPort > 0 { + attrs = append(attrs, semconvNew.NetworkPeerPort(peerPort)) + } + } + + if useragent := req.UserAgent(); useragent != "" { + attrs = append(attrs, semconvNew.UserAgentOriginal(useragent)) + } + + if clientIP != "" { + attrs = append(attrs, semconvNew.ClientAddress(clientIP)) + } + + if req.URL != nil && req.URL.Path != "" { + attrs = append(attrs, semconvNew.URLPath(req.URL.Path)) + } + + if protoName != "" && protoName != "http" { + attrs = append(attrs, semconvNew.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attrs = append(attrs, semconvNew.NetworkProtocolVersion(protoVersion)) + } + + return attrs +} + +func (n CurrentHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { + if method == "" { + return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} + } + if attr, ok := methodLookup[method]; ok { + return attr, attribute.KeyValue{} + } + + orig := semconvNew.HTTPRequestMethodOriginal(method) + if attr, ok := methodLookup[strings.ToUpper(method)]; ok { + return attr, orig + } + return semconvNew.HTTPRequestMethodGet, orig +} + +func (n CurrentHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive + if https { + return semconvNew.URLScheme("https") + } + return semconvNew.URLScheme("http") +} + +// TraceResponse returns trace attributes for telemetry from an HTTP response. +// +// If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. +func (n CurrentHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { + var count int + + if resp.ReadBytes > 0 { + count++ + } + if resp.WriteBytes > 0 { + count++ + } + if resp.StatusCode > 0 { + count++ + } + + attributes := make([]attribute.KeyValue, 0, count) + + if resp.ReadBytes > 0 { + attributes = append(attributes, + semconvNew.HTTPRequestBodySize(int(resp.ReadBytes)), + ) + } + if resp.WriteBytes > 0 { + attributes = append(attributes, + semconvNew.HTTPResponseBodySize(int(resp.WriteBytes)), + ) + } + if resp.StatusCode > 0 { + attributes = append(attributes, + semconvNew.HTTPResponseStatusCode(resp.StatusCode), + ) + } + + return attributes +} + +// Route returns the attribute for the route. +func (n CurrentHTTPServer) Route(route string) attribute.KeyValue { + return semconvNew.HTTPRoute(route) +} + +type CurrentHTTPClient struct{} + +// RequestTraceAttrs returns trace attributes for an HTTP request made by a client. +func (n CurrentHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { + /* + below attributes are returned: + - http.request.method + - http.request.method.original + - url.full + - server.address + - server.port + - network.protocol.name + - network.protocol.version + */ + numOfAttributes := 3 // URL, server address, proto, and method. + + var urlHost string + if req.URL != nil { + urlHost = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{urlHost, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + eligiblePort := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if eligiblePort > 0 { + numOfAttributes++ + } + useragent := req.UserAgent() + if useragent != "" { + numOfAttributes++ + } + + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" && protoName != "http" { + numOfAttributes++ + } + if protoVersion != "" { + numOfAttributes++ + } + + method, originalMethod := n.method(req.Method) + if originalMethod != (attribute.KeyValue{}) { + numOfAttributes++ + } + + attrs := make([]attribute.KeyValue, 0, numOfAttributes) + + attrs = append(attrs, method) + if originalMethod != (attribute.KeyValue{}) { + attrs = append(attrs, originalMethod) + } + + var u string + if req.URL != nil { + // Remove any username/password info that may be in the URL. + userinfo := req.URL.User + req.URL.User = nil + u = req.URL.String() + // Restore any username/password info that was removed. + req.URL.User = userinfo + } + attrs = append(attrs, semconvNew.URLFull(u)) + + attrs = append(attrs, semconvNew.ServerAddress(requestHost)) + if eligiblePort > 0 { + attrs = append(attrs, semconvNew.ServerPort(eligiblePort)) + } + + if protoName != "" && protoName != "http" { + attrs = append(attrs, semconvNew.NetworkProtocolName(protoName)) + } + if protoVersion != "" { + attrs = append(attrs, semconvNew.NetworkProtocolVersion(protoVersion)) + } + + return attrs +} + +// ResponseTraceAttrs returns trace attributes for an HTTP response made by a client. +func (n CurrentHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { + /* + below attributes are returned: + - http.response.status_code + - error.type + */ + var count int + if resp.StatusCode > 0 { + count++ + } + + if isErrorStatusCode(resp.StatusCode) { + count++ + } + + attrs := make([]attribute.KeyValue, 0, count) + if resp.StatusCode > 0 { + attrs = append(attrs, semconvNew.HTTPResponseStatusCode(resp.StatusCode)) + } + + if isErrorStatusCode(resp.StatusCode) { + errorType := strconv.Itoa(resp.StatusCode) + attrs = append(attrs, semconvNew.ErrorTypeKey.String(errorType)) + } + return attrs +} + +func (n CurrentHTTPClient) ErrorType(err error) attribute.KeyValue { + t := reflect.TypeOf(err) + var value string + if t.PkgPath() == "" && t.Name() == "" { + // Likely a builtin type. + value = t.String() + } else { + value = fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) + } + + if value == "" { + return semconvNew.ErrorTypeOther + } + + return semconvNew.ErrorTypeKey.String(value) +} + +func (n CurrentHTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) { + if method == "" { + return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} + } + if attr, ok := methodLookup[method]; ok { + return attr, attribute.KeyValue{} + } + + orig := semconvNew.HTTPRequestMethodOriginal(method) + if attr, ok := methodLookup[strings.ToUpper(method)]; ok { + return attr, orig + } + return semconvNew.HTTPRequestMethodGet, orig +} + +func isErrorStatusCode(code int) bool { + return code >= 400 || code < 100 +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go index e7f293761..93e8d0f94 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go @@ -9,18 +9,19 @@ import ( "strconv" "strings" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" - semconvNew "go.opentelemetry.io/otel/semconv/v1.24.0" + semconvNew "go.opentelemetry.io/otel/semconv/v1.26.0" ) -// splitHostPort splits a network address hostport of the form "host", +// SplitHostPort splits a network address hostport of the form "host", // "host%zone", "[host]", "[host%zone], "host:port", "host%zone:port", // "[host]:port", "[host%zone]:port", or ":port" into host or host%zone and // port. // // An empty host is returned if it is not provided or unparsable. A negative // port is returned if it is not provided or unparsable. -func splitHostPort(hostport string) (host string, port int) { +func SplitHostPort(hostport string) (host string, port int) { port = -1 if strings.HasPrefix(hostport, "[") { @@ -49,7 +50,7 @@ func splitHostPort(hostport string) (host string, port int) { if err != nil { return } - return host, int(p) + return host, int(p) // nolint: gosec // Byte size checked 16 above. } func requiredHTTPPort(https bool, port int) int { // nolint:revive @@ -89,3 +90,9 @@ var methodLookup = map[string]attribute.KeyValue{ http.MethodPut: semconvNew.HTTPRequestMethodPut, http.MethodTrace: semconvNew.HTTPRequestMethodTrace, } + +func handleErr(err error) { + if err != nil { + otel.Handle(err) + } +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go index c3e838aaa..c042249dd 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.20.0.go @@ -7,13 +7,17 @@ import ( "errors" "io" "net/http" + "slices" + "strings" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/noop" semconv "go.opentelemetry.io/otel/semconv/v1.20.0" ) -type oldHTTPServer struct{} +type OldHTTPServer struct{} // RequestTraceAttrs returns trace attributes for an HTTP request received by a // server. @@ -31,14 +35,14 @@ type oldHTTPServer struct{} // // If the primary server name is not known, server should be an empty string. // The req Host will be used to determine the server instead. -func (o oldHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { +func (o OldHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { return semconvutil.HTTPServerRequest(server, req) } // ResponseTraceAttrs returns trace attributes for telemetry from an HTTP response. // // If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (o oldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { +func (o OldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { attributes := []attribute.KeyValue{} if resp.ReadBytes > 0 { @@ -63,7 +67,7 @@ func (o oldHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.Ke } // Route returns the attribute for the route. -func (o oldHTTPServer) Route(route string) attribute.KeyValue { +func (o OldHTTPServer) Route(route string) attribute.KeyValue { return semconv.HTTPRoute(route) } @@ -72,3 +76,199 @@ func (o oldHTTPServer) Route(route string) attribute.KeyValue { func HTTPStatusCode(status int) attribute.KeyValue { return semconv.HTTPStatusCode(status) } + +// Server HTTP metrics. +const ( + serverRequestSize = "http.server.request.size" // Incoming request bytes total + serverResponseSize = "http.server.response.size" // Incoming response bytes total + serverDuration = "http.server.duration" // Incoming end to end duration, milliseconds +) + +func (h OldHTTPServer) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { + if meter == nil { + return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} + } + var err error + requestBytesCounter, err := meter.Int64Counter( + serverRequestSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP request messages."), + ) + handleErr(err) + + responseBytesCounter, err := meter.Int64Counter( + serverResponseSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP response messages."), + ) + handleErr(err) + + serverLatencyMeasure, err := meter.Float64Histogram( + serverDuration, + metric.WithUnit("ms"), + metric.WithDescription("Measures the duration of inbound HTTP requests."), + ) + handleErr(err) + + return requestBytesCounter, responseBytesCounter, serverLatencyMeasure +} + +func (o OldHTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + n := len(additionalAttributes) + 3 + var host string + var p int + if server == "" { + host, p = SplitHostPort(req.Host) + } else { + // Prioritize the primary server name. + host, p = SplitHostPort(server) + if p < 0 { + _, p = SplitHostPort(req.Host) + } + } + hostPort := requiredHTTPPort(req.TLS != nil, p) + if hostPort > 0 { + n++ + } + protoName, protoVersion := netProtocol(req.Proto) + if protoName != "" { + n++ + } + if protoVersion != "" { + n++ + } + + if statusCode > 0 { + n++ + } + + attributes := slices.Grow(additionalAttributes, n) + attributes = append(attributes, + standardizeHTTPMethodMetric(req.Method), + o.scheme(req.TLS != nil), + semconv.NetHostName(host)) + + if hostPort > 0 { + attributes = append(attributes, semconv.NetHostPort(hostPort)) + } + if protoName != "" { + attributes = append(attributes, semconv.NetProtocolName(protoName)) + } + if protoVersion != "" { + attributes = append(attributes, semconv.NetProtocolVersion(protoVersion)) + } + + if statusCode > 0 { + attributes = append(attributes, semconv.HTTPStatusCode(statusCode)) + } + return attributes +} + +func (o OldHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive + if https { + return semconv.HTTPSchemeHTTPS + } + return semconv.HTTPSchemeHTTP +} + +type OldHTTPClient struct{} + +func (o OldHTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue { + return semconvutil.HTTPClientRequest(req) +} + +func (o OldHTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue { + return semconvutil.HTTPClientResponse(resp) +} + +func (o OldHTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue { + /* The following semantic conventions are returned if present: + http.method string + http.status_code int + net.peer.name string + net.peer.port int + */ + + n := 2 // method, peer name. + var h string + if req.URL != nil { + h = req.URL.Host + } + var requestHost string + var requestPort int + for _, hostport := range []string{h, req.Header.Get("Host")} { + requestHost, requestPort = SplitHostPort(hostport) + if requestHost != "" || requestPort > 0 { + break + } + } + + port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort) + if port > 0 { + n++ + } + + if statusCode > 0 { + n++ + } + + attributes := slices.Grow(additionalAttributes, n) + attributes = append(attributes, + standardizeHTTPMethodMetric(req.Method), + semconv.NetPeerName(requestHost), + ) + + if port > 0 { + attributes = append(attributes, semconv.NetPeerPort(port)) + } + + if statusCode > 0 { + attributes = append(attributes, semconv.HTTPStatusCode(statusCode)) + } + return attributes +} + +// Client HTTP metrics. +const ( + clientRequestSize = "http.client.request.size" // Incoming request bytes total + clientResponseSize = "http.client.response.size" // Incoming response bytes total + clientDuration = "http.client.duration" // Incoming end to end duration, milliseconds +) + +func (o OldHTTPClient) createMeasures(meter metric.Meter) (metric.Int64Counter, metric.Int64Counter, metric.Float64Histogram) { + if meter == nil { + return noop.Int64Counter{}, noop.Int64Counter{}, noop.Float64Histogram{} + } + requestBytesCounter, err := meter.Int64Counter( + clientRequestSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP request messages."), + ) + handleErr(err) + + responseBytesCounter, err := meter.Int64Counter( + clientResponseSize, + metric.WithUnit("By"), + metric.WithDescription("Measures the size of HTTP response messages."), + ) + handleErr(err) + + latencyMeasure, err := meter.Float64Histogram( + clientDuration, + metric.WithUnit("ms"), + metric.WithDescription("Measures the duration of outbound HTTP requests."), + ) + handleErr(err) + + return requestBytesCounter, responseBytesCounter, latencyMeasure +} + +func standardizeHTTPMethodMetric(method string) attribute.KeyValue { + method = strings.ToUpper(method) + switch method { + case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace: + default: + method = "_OTHER" + } + return semconv.HTTPMethod(method) +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.24.0.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.24.0.go deleted file mode 100644 index 0c5d4c460..000000000 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/v1.24.0.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" - -import ( - "net/http" - "strings" - - "go.opentelemetry.io/otel/attribute" - semconvNew "go.opentelemetry.io/otel/semconv/v1.24.0" -) - -type newHTTPServer struct{} - -// TraceRequest returns trace attributes for an HTTP request received by a -// server. -// -// The server must be the primary server name if it is known. For example this -// would be the ServerName directive -// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache -// server, and the server_name directive -// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an -// nginx server. More generically, the primary server name would be the host -// header value that matches the default virtual host of an HTTP server. It -// should include the host identifier and if a port is used to route to the -// server that port identifier should be included as an appropriate port -// suffix. -// -// If the primary server name is not known, server should be an empty string. -// The req Host will be used to determine the server instead. -func (n newHTTPServer) RequestTraceAttrs(server string, req *http.Request) []attribute.KeyValue { - count := 3 // ServerAddress, Method, Scheme - - var host string - var p int - if server == "" { - host, p = splitHostPort(req.Host) - } else { - // Prioritize the primary server name. - host, p = splitHostPort(server) - if p < 0 { - _, p = splitHostPort(req.Host) - } - } - - hostPort := requiredHTTPPort(req.TLS != nil, p) - if hostPort > 0 { - count++ - } - - method, methodOriginal := n.method(req.Method) - if methodOriginal != (attribute.KeyValue{}) { - count++ - } - - scheme := n.scheme(req.TLS != nil) - - if peer, peerPort := splitHostPort(req.RemoteAddr); peer != "" { - // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a - // file-path that would be interpreted with a sock family. - count++ - if peerPort > 0 { - count++ - } - } - - useragent := req.UserAgent() - if useragent != "" { - count++ - } - - clientIP := serverClientIP(req.Header.Get("X-Forwarded-For")) - if clientIP != "" { - count++ - } - - if req.URL != nil && req.URL.Path != "" { - count++ - } - - protoName, protoVersion := netProtocol(req.Proto) - if protoName != "" && protoName != "http" { - count++ - } - if protoVersion != "" { - count++ - } - - attrs := make([]attribute.KeyValue, 0, count) - attrs = append(attrs, - semconvNew.ServerAddress(host), - method, - scheme, - ) - - if hostPort > 0 { - attrs = append(attrs, semconvNew.ServerPort(hostPort)) - } - if methodOriginal != (attribute.KeyValue{}) { - attrs = append(attrs, methodOriginal) - } - - if peer, peerPort := splitHostPort(req.RemoteAddr); peer != "" { - // The Go HTTP server sets RemoteAddr to "IP:port", this will not be a - // file-path that would be interpreted with a sock family. - attrs = append(attrs, semconvNew.NetworkPeerAddress(peer)) - if peerPort > 0 { - attrs = append(attrs, semconvNew.NetworkPeerPort(peerPort)) - } - } - - if useragent := req.UserAgent(); useragent != "" { - attrs = append(attrs, semconvNew.UserAgentOriginal(useragent)) - } - - if clientIP != "" { - attrs = append(attrs, semconvNew.ClientAddress(clientIP)) - } - - if req.URL != nil && req.URL.Path != "" { - attrs = append(attrs, semconvNew.URLPath(req.URL.Path)) - } - - if protoName != "" && protoName != "http" { - attrs = append(attrs, semconvNew.NetworkProtocolName(protoName)) - } - if protoVersion != "" { - attrs = append(attrs, semconvNew.NetworkProtocolVersion(protoVersion)) - } - - return attrs -} - -func (n newHTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) { - if method == "" { - return semconvNew.HTTPRequestMethodGet, attribute.KeyValue{} - } - if attr, ok := methodLookup[method]; ok { - return attr, attribute.KeyValue{} - } - - orig := semconvNew.HTTPRequestMethodOriginal(method) - if attr, ok := methodLookup[strings.ToUpper(method)]; ok { - return attr, orig - } - return semconvNew.HTTPRequestMethodGet, orig -} - -func (n newHTTPServer) scheme(https bool) attribute.KeyValue { // nolint:revive - if https { - return semconvNew.URLScheme("https") - } - return semconvNew.URLScheme("http") -} - -// TraceResponse returns trace attributes for telemetry from an HTTP response. -// -// If any of the fields in the ResponseTelemetry are not set the attribute will be omitted. -func (n newHTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue { - var count int - - if resp.ReadBytes > 0 { - count++ - } - if resp.WriteBytes > 0 { - count++ - } - if resp.StatusCode > 0 { - count++ - } - - attributes := make([]attribute.KeyValue, 0, count) - - if resp.ReadBytes > 0 { - attributes = append(attributes, - semconvNew.HTTPRequestBodySize(int(resp.ReadBytes)), - ) - } - if resp.WriteBytes > 0 { - attributes = append(attributes, - semconvNew.HTTPResponseBodySize(int(resp.WriteBytes)), - ) - } - if resp.StatusCode > 0 { - attributes = append(attributes, - semconvNew.HTTPResponseStatusCode(resp.StatusCode), - ) - } - - return attributes -} - -// Route returns the attribute for the route. -func (n newHTTPServer) Route(route string) attribute.KeyValue { - return semconvNew.HTTPRoute(route) -} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go index a9a9226b3..b80a1db61 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil/netconv.go @@ -195,7 +195,7 @@ func splitHostPort(hostport string) (host string, port int) { if err != nil { return } - return host, int(p) + return host, int(p) // nolint: gosec // Bitsize checked to be 16 above. } func netProtocol(proto string) (name string, version string) { diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go new file mode 100644 index 000000000..9476ef01b --- /dev/null +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/start_time_context.go @@ -0,0 +1,29 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + +import ( + "context" + "time" +) + +type startTimeContextKeyType int + +const startTimeContextKey startTimeContextKeyType = 0 + +// ContextWithStartTime returns a new context with the provided start time. The +// start time will be used for metrics and traces emitted by the +// instrumentation. Only one labeller can be injected into the context. +// Injecting it multiple times will override the previous calls. +func ContextWithStartTime(parent context.Context, start time.Time) context.Context { + return context.WithValue(parent, startTimeContextKey, start) +} + +// StartTimeFromContext retrieves a time.Time from the provided context if one +// is available. If no start time was found in the provided context, a new, +// zero start time is returned and the second return value is false. +func StartTimeFromContext(ctx context.Context) time.Time { + t, _ := ctx.Value(startTimeContextKey).(time.Time) + return t +} diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go index 0d3cb2e4a..39681ad4b 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/transport.go @@ -11,13 +11,13 @@ import ( "sync/atomic" "time" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" - semconv "go.opentelemetry.io/otel/semconv/v1.20.0" + "go.opentelemetry.io/otel/trace" ) @@ -26,17 +26,15 @@ import ( type Transport struct { rt http.RoundTripper - tracer trace.Tracer - meter metric.Meter - propagators propagation.TextMapPropagator - spanStartOptions []trace.SpanStartOption - filters []Filter - spanNameFormatter func(string, *http.Request) string - clientTrace func(context.Context) *httptrace.ClientTrace + tracer trace.Tracer + propagators propagation.TextMapPropagator + spanStartOptions []trace.SpanStartOption + filters []Filter + spanNameFormatter func(string, *http.Request) string + clientTrace func(context.Context) *httptrace.ClientTrace + metricAttributesFn func(*http.Request) []attribute.KeyValue - requestBytesCounter metric.Int64Counter - responseBytesCounter metric.Int64Counter - latencyMeasure metric.Float64Histogram + semconv semconv.HTTPClient } var _ http.RoundTripper = &Transport{} @@ -63,43 +61,19 @@ func NewTransport(base http.RoundTripper, opts ...Option) *Transport { c := newConfig(append(defaultOpts, opts...)...) t.applyConfig(c) - t.createMeasures() return &t } func (t *Transport) applyConfig(c *config) { t.tracer = c.Tracer - t.meter = c.Meter t.propagators = c.Propagators t.spanStartOptions = c.SpanStartOptions t.filters = c.Filters t.spanNameFormatter = c.SpanNameFormatter t.clientTrace = c.ClientTrace -} - -func (t *Transport) createMeasures() { - var err error - t.requestBytesCounter, err = t.meter.Int64Counter( - clientRequestSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP request messages."), - ) - handleErr(err) - - t.responseBytesCounter, err = t.meter.Int64Counter( - clientResponseSize, - metric.WithUnit("By"), - metric.WithDescription("Measures the size of HTTP response messages."), - ) - handleErr(err) - - t.latencyMeasure, err = t.meter.Float64Histogram( - clientDuration, - metric.WithUnit("ms"), - metric.WithDescription("Measures the duration of outbound HTTP requests."), - ) - handleErr(err) + t.semconv = semconv.NewHTTPClient(c.Meter) + t.metricAttributesFn = c.MetricAttributesFn } func defaultTransportFormatter(_ string, r *http.Request) string { @@ -143,54 +117,68 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { r = r.Clone(ctx) // According to RoundTripper spec, we shouldn't modify the origin request. - // use a body wrapper to determine the request size - var bw bodyWrapper // if request body is nil or NoBody, we don't want to mutate the body as it // will affect the identity of it in an unforeseeable way because we assert // ReadCloser fulfills a certain interface and it is indeed nil or NoBody. + bw := request.NewBodyWrapper(r.Body, func(int64) {}) if r.Body != nil && r.Body != http.NoBody { - bw.ReadCloser = r.Body - // noop to prevent nil panic. not using this record fun yet. - bw.record = func(int64) {} - r.Body = &bw + r.Body = bw } - span.SetAttributes(semconvutil.HTTPClientRequest(r)...) + span.SetAttributes(t.semconv.RequestTraceAttrs(r)...) t.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header)) res, err := t.rt.RoundTrip(r) if err != nil { - span.RecordError(err) + // set error type attribute if the error is part of the predefined + // error types. + // otherwise, record it as an exception + if errType := t.semconv.ErrorType(err); errType.Valid() { + span.SetAttributes(errType) + } else { + span.RecordError(err) + } + span.SetStatus(codes.Error, err.Error()) span.End() return res, err } // metrics - metricAttrs := append(labeler.Get(), semconvutil.HTTPClientRequestMetrics(r)...) - if res.StatusCode > 0 { - metricAttrs = append(metricAttrs, semconv.HTTPStatusCode(res.StatusCode)) - } - o := metric.WithAttributeSet(attribute.NewSet(metricAttrs...)) - addOpts := []metric.AddOption{o} // Allocate vararg slice once. - t.requestBytesCounter.Add(ctx, bw.read.Load(), addOpts...) + metricOpts := t.semconv.MetricOptions(semconv.MetricAttributes{ + Req: r, + StatusCode: res.StatusCode, + AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...), + }) + // For handling response bytes we leverage a callback when the client reads the http response readRecordFunc := func(n int64) { - t.responseBytesCounter.Add(ctx, n, addOpts...) + t.semconv.RecordResponseSize(ctx, n, metricOpts.AddOptions()) } // traces - span.SetAttributes(semconvutil.HTTPClientResponse(res)...) - span.SetStatus(semconvutil.HTTPClientStatus(res.StatusCode)) + span.SetAttributes(t.semconv.ResponseTraceAttrs(res)...) + span.SetStatus(t.semconv.Status(res.StatusCode)) res.Body = newWrappedBody(span, readRecordFunc, res.Body) // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - t.latencyMeasure.Record(ctx, elapsedTime, o) + t.semconv.RecordMetrics(ctx, semconv.MetricData{ + RequestSize: bw.BytesRead(), + ElapsedTime: elapsedTime, + }, metricOpts) - return res, err + return res, nil +} + +func (t *Transport) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue { + var attributeForRequest []attribute.KeyValue + if t.metricAttributesFn != nil { + attributeForRequest = t.metricAttributesFn(r) + } + return attributeForRequest } // newWrappedBody returns a new and appropriately scoped *wrappedBody as an diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index b0957f28c..353e43b91 100644 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -5,7 +5,7 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.53.0" + return "0.58.0" // This string is updated by the pre_release.sh script during release } diff --git a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go b/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go deleted file mode 100644 index 948f8406c..000000000 --- a/e2e/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" - -import ( - "context" - "io" - "net/http" - "sync/atomic" - - "go.opentelemetry.io/otel/propagation" -) - -var _ io.ReadCloser = &bodyWrapper{} - -// bodyWrapper wraps a http.Request.Body (an io.ReadCloser) to track the number -// of bytes read and the last error. -type bodyWrapper struct { - io.ReadCloser - record func(n int64) // must not be nil - - read atomic.Int64 - err error -} - -func (w *bodyWrapper) Read(b []byte) (int, error) { - n, err := w.ReadCloser.Read(b) - n1 := int64(n) - w.read.Add(n1) - w.err = err - w.record(n1) - return n, err -} - -func (w *bodyWrapper) Close() error { - return w.ReadCloser.Close() -} - -var _ http.ResponseWriter = &respWriterWrapper{} - -// respWriterWrapper wraps a http.ResponseWriter in order to track the number of -// bytes written, the last error, and to catch the first written statusCode. -// TODO: The wrapped http.ResponseWriter doesn't implement any of the optional -// types (http.Hijacker, http.Pusher, http.CloseNotifier, http.Flusher, etc) -// that may be useful when using it in real life situations. -type respWriterWrapper struct { - http.ResponseWriter - record func(n int64) // must not be nil - - // used to inject the header - ctx context.Context - - props propagation.TextMapPropagator - - written int64 - statusCode int - err error - wroteHeader bool -} - -func (w *respWriterWrapper) Header() http.Header { - return w.ResponseWriter.Header() -} - -func (w *respWriterWrapper) Write(p []byte) (int, error) { - if !w.wroteHeader { - w.WriteHeader(http.StatusOK) - } - n, err := w.ResponseWriter.Write(p) - n1 := int64(n) - w.record(n1) - w.written += n1 - w.err = err - return n, err -} - -// WriteHeader persists initial statusCode for span attribution. -// All calls to WriteHeader will be propagated to the underlying ResponseWriter -// and will persist the statusCode from the first call. -// Blocking consecutive calls to WriteHeader alters expected behavior and will -// remove warning logs from net/http where developers will notice incorrect handler implementations. -func (w *respWriterWrapper) WriteHeader(statusCode int) { - if !w.wroteHeader { - w.wroteHeader = true - w.statusCode = statusCode - } - w.ResponseWriter.WriteHeader(statusCode) -} - -func (w *respWriterWrapper) Flush() { - if !w.wroteHeader { - w.WriteHeader(http.StatusOK) - } - - if f, ok := w.ResponseWriter.(http.Flusher); ok { - f.Flush() - } -} diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go index f6dd3decc..2e7690e43 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go @@ -13,7 +13,8 @@ func InstrumentationScope(il instrumentation.Scope) *commonpb.InstrumentationSco return nil } return &commonpb.InstrumentationScope{ - Name: il.Name, - Version: il.Version, + Name: il.Name, + Version: il.Version, + Attributes: Iterator(il.Attributes.Iter()), } } diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go index c3c69c5a0..bf27ef022 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go @@ -4,6 +4,8 @@ package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" import ( + "math" + "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/sdk/instrumentation" @@ -95,16 +97,16 @@ func span(sd tracesdk.ReadOnlySpan) *tracepb.Span { SpanId: sid[:], TraceState: sd.SpanContext().TraceState().String(), Status: status(sd.Status().Code, sd.Status().Description), - StartTimeUnixNano: uint64(sd.StartTime().UnixNano()), - EndTimeUnixNano: uint64(sd.EndTime().UnixNano()), + StartTimeUnixNano: uint64(max(0, sd.StartTime().UnixNano())), // nolint:gosec // Overflow checked. + EndTimeUnixNano: uint64(max(0, sd.EndTime().UnixNano())), // nolint:gosec // Overflow checked. Links: links(sd.Links()), Kind: spanKind(sd.SpanKind()), Name: sd.Name(), Attributes: KeyValues(sd.Attributes()), Events: spanEvents(sd.Events()), - DroppedAttributesCount: uint32(sd.DroppedAttributes()), - DroppedEventsCount: uint32(sd.DroppedEvents()), - DroppedLinksCount: uint32(sd.DroppedLinks()), + DroppedAttributesCount: clampUint32(sd.DroppedAttributes()), + DroppedEventsCount: clampUint32(sd.DroppedEvents()), + DroppedLinksCount: clampUint32(sd.DroppedLinks()), } if psid := sd.Parent().SpanID(); psid.IsValid() { @@ -115,6 +117,16 @@ func span(sd tracesdk.ReadOnlySpan) *tracepb.Span { return s } +func clampUint32(v int) uint32 { + if v < 0 { + return 0 + } + if int64(v) > math.MaxUint32 { + return math.MaxUint32 + } + return uint32(v) // nolint: gosec // Overflow/Underflow checked. +} + // status transform a span code and message into an OTLP span status. func status(status codes.Code, message string) *tracepb.Status { var c tracepb.Status_StatusCode @@ -153,7 +165,7 @@ func links(links []tracesdk.Link) []*tracepb.Span_Link { TraceId: tid[:], SpanId: sid[:], Attributes: KeyValues(otLink.Attributes), - DroppedAttributesCount: uint32(otLink.DroppedAttributeCount), + DroppedAttributesCount: clampUint32(otLink.DroppedAttributeCount), Flags: flags, }) } @@ -166,7 +178,7 @@ func buildSpanFlags(sc trace.SpanContext) uint32 { flags |= tracepb.SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK } - return uint32(flags) + return uint32(flags) // nolint:gosec // Flags is a bitmask and can't be negative } // spanEvents transforms span Events to an OTLP span events. @@ -180,9 +192,9 @@ func spanEvents(es []tracesdk.Event) []*tracepb.Span_Event { for i := 0; i < len(es); i++ { events[i] = &tracepb.Span_Event{ Name: es[i].Name, - TimeUnixNano: uint64(es[i].Time.UnixNano()), + TimeUnixNano: uint64(max(0, es[i].Time.UnixNano())), // nolint:gosec // Overflow checked. Attributes: KeyValues(es[i].Attributes), - DroppedAttributesCount: uint32(es[i].DroppedAttributeCount), + DroppedAttributesCount: clampUint32(es[i].DroppedAttributeCount), } } return events diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go index 3993df927..2171bee3c 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go @@ -229,7 +229,12 @@ func (c *client) exportContext(parent context.Context) (context.Context, context } if c.metadata.Len() > 0 { - ctx = metadata.NewOutgoingContext(ctx, c.metadata) + md := c.metadata + if outMD, ok := metadata.FromOutgoingContext(ctx); ok { + md = metadata.Join(md, outMD) + } + + ctx = metadata.NewOutgoingContext(ctx, md) } // Unify the client stopCtx with the parent. diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go index e783b57ac..b7bd429ff 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/doc.go @@ -12,9 +12,8 @@ The environment variables described below can be used for configuration. OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (default: "https://localhost:4317") - target to which the exporter sends telemetry. The target syntax is defined in https://github.com/grpc/grpc/blob/master/doc/naming.md. -The value must contain a host. -The value may additionally a port, a scheme, and a path. -The value accepts "http" and "https" scheme. +The value must contain a scheme ("http" or "https") and host. +The value may additionally contain a port, and a path. The value should not contain a query string or fragment. OTEL_EXPORTER_OTLP_TRACES_ENDPOINT takes precedence over OTEL_EXPORTER_OTLP_ENDPOINT. The configuration can be overridden by [WithEndpoint], [WithEndpointURL], [WithInsecure], and [WithGRPCConn] options. diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig/envconfig.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig/envconfig.go index 9513c0a57..4abf48d1f 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig/envconfig.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig/envconfig.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "time" + "unicode" "go.opentelemetry.io/otel/internal/global" ) @@ -163,12 +164,16 @@ func stringToHeader(value string) map[string]string { global.Error(errors.New("missing '="), "parse headers", "input", header) continue } - name, err := url.PathUnescape(n) - if err != nil { - global.Error(err, "escape header key", "key", n) + + trimmedName := strings.TrimSpace(n) + + // Validate the key. + if !isValidHeaderKey(trimmedName) { + global.Error(errors.New("invalid header key"), "parse headers", "key", trimmedName) continue } - trimmedName := strings.TrimSpace(name) + + // Only decode the value. value, err := url.PathUnescape(v) if err != nil { global.Error(err, "escape header value", "value", v) @@ -189,3 +194,22 @@ func createCertPool(certBytes []byte) (*x509.CertPool, error) { } return cp, nil } + +func isValidHeaderKey(key string) bool { + if key == "" { + return false + } + for _, c := range key { + if !isTokenChar(c) { + return false + } + } + return true +} + +func isTokenChar(c rune) bool { + return c <= unicode.MaxASCII && (unicode.IsLetter(c) || + unicode.IsDigit(c) || + c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || + c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~') +} diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go index 8f84a7996..0a317d926 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/otlpconfig/options.go @@ -98,7 +98,7 @@ func cleanPath(urlPath string, defaultPath string) string { return defaultPath } if !path.IsAbs(tmp) { - tmp = fmt.Sprintf("/%s", tmp) + tmp = "/" + tmp } return tmp } @@ -125,7 +125,7 @@ func NewGRPCConfig(opts ...GRPCOption) Config { if cfg.ServiceConfig != "" { cfg.DialOptions = append(cfg.DialOptions, grpc.WithDefaultServiceConfig(cfg.ServiceConfig)) } - // Priroritize GRPCCredentials over Insecure (passing both is an error). + // Prioritize GRPCCredentials over Insecure (passing both is an error). if cfg.Traces.GRPCCredentials != nil { cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(cfg.Traces.GRPCCredentials)) } else if cfg.Traces.Insecure { @@ -278,9 +278,7 @@ func WithEndpointURL(v string) GenericOption { cfg.Traces.Endpoint = u.Host cfg.Traces.URLPath = u.Path - if u.Scheme != "https" { - cfg.Traces.Insecure = true - } + cfg.Traces.Insecure = u.Scheme != "https" return cfg }) diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go index 4f2113ae2..1c5450ab6 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/retry/retry.go @@ -112,7 +112,7 @@ func (c Config) RequestFunc(evaluate EvaluateFunc) RequestFunc { } if ctxErr := waitFunc(ctx, delay); ctxErr != nil { - return fmt.Errorf("%w: %s", ctxErr, err) + return fmt.Errorf("%w: %w", ctxErr, err) } } } diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go index bbad0e6d0..00ab1f20c 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go @@ -59,8 +59,9 @@ func WithInsecure() Option { // // If the OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT // environment variable is set, and this option is not passed, that variable -// value will be used. If both are set, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT -// will take precedence. +// value will be used. If both environment variables are set, +// OTEL_EXPORTER_OTLP_TRACES_ENDPOINT will take precedence. If an environment +// variable is set, and this option is passed, this option will take precedence. // // If both this option and WithEndpointURL are used, the last used option will // take precedence. @@ -79,8 +80,9 @@ func WithEndpoint(endpoint string) Option { // // If the OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT // environment variable is set, and this option is not passed, that variable -// value will be used. If both are set, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT -// will take precedence. +// value will be used. If both environment variables are set, +// OTEL_EXPORTER_OTLP_TRACES_ENDPOINT will take precedence. If an environment +// variable is set, and this option is passed, this option will take precedence. // // If both this option and WithEndpoint are used, the last used option will // take precedence. diff --git a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go index 14ad8c33b..8ea156a09 100644 --- a/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go +++ b/e2e/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -5,5 +5,5 @@ package otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace" // Version is the current release version of the OpenTelemetry OTLP trace exporter in use. func Version() string { - return "1.28.0" + return "1.33.0" } diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/README.md b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/README.md deleted file mode 100644 index 0b6cbe960..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Semconv v1.24.0 - -[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/semconv/v1.24.0)](https://pkg.go.dev/go.opentelemetry.io/otel/semconv/v1.24.0) diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go deleted file mode 100644 index 6e688345c..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go +++ /dev/null @@ -1,4387 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -import "go.opentelemetry.io/otel/attribute" - -// Describes FaaS attributes. -const ( - // FaaSInvokedNameKey is the attribute Key conforming to the - // "faas.invoked_name" semantic conventions. It represents the name of the - // invoked function. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'my-function' - // Note: SHOULD be equal to the `faas.name` resource attribute of the - // invoked function. - FaaSInvokedNameKey = attribute.Key("faas.invoked_name") - - // FaaSInvokedProviderKey is the attribute Key conforming to the - // "faas.invoked_provider" semantic conventions. It represents the cloud - // provider of the invoked function. - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - // Note: SHOULD be equal to the `cloud.provider` resource attribute of the - // invoked function. - FaaSInvokedProviderKey = attribute.Key("faas.invoked_provider") - - // FaaSInvokedRegionKey is the attribute Key conforming to the - // "faas.invoked_region" semantic conventions. It represents the cloud - // region of the invoked function. - // - // Type: string - // RequirementLevel: ConditionallyRequired (For some cloud providers, like - // AWS or GCP, the region in which a function is hosted is essential to - // uniquely identify the function and also part of its endpoint. Since it's - // part of the endpoint being called, the region is always known to - // clients. In these cases, `faas.invoked_region` MUST be set accordingly. - // If the region is unknown to the client or not required for identifying - // the invoked function, setting `faas.invoked_region` is optional.) - // Stability: experimental - // Examples: 'eu-central-1' - // Note: SHOULD be equal to the `cloud.region` resource attribute of the - // invoked function. - FaaSInvokedRegionKey = attribute.Key("faas.invoked_region") - - // FaaSTriggerKey is the attribute Key conforming to the "faas.trigger" - // semantic conventions. It represents the type of the trigger which caused - // this function invocation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - FaaSTriggerKey = attribute.Key("faas.trigger") -) - -var ( - // Alibaba Cloud - FaaSInvokedProviderAlibabaCloud = FaaSInvokedProviderKey.String("alibaba_cloud") - // Amazon Web Services - FaaSInvokedProviderAWS = FaaSInvokedProviderKey.String("aws") - // Microsoft Azure - FaaSInvokedProviderAzure = FaaSInvokedProviderKey.String("azure") - // Google Cloud Platform - FaaSInvokedProviderGCP = FaaSInvokedProviderKey.String("gcp") - // Tencent Cloud - FaaSInvokedProviderTencentCloud = FaaSInvokedProviderKey.String("tencent_cloud") -) - -var ( - // A response to some data source operation such as a database or filesystem read/write - FaaSTriggerDatasource = FaaSTriggerKey.String("datasource") - // To provide an answer to an inbound HTTP request - FaaSTriggerHTTP = FaaSTriggerKey.String("http") - // A function is set to be executed when messages are sent to a messaging system - FaaSTriggerPubsub = FaaSTriggerKey.String("pubsub") - // A function is scheduled to be executed regularly - FaaSTriggerTimer = FaaSTriggerKey.String("timer") - // If none of the others apply - FaaSTriggerOther = FaaSTriggerKey.String("other") -) - -// FaaSInvokedName returns an attribute KeyValue conforming to the -// "faas.invoked_name" semantic conventions. It represents the name of the -// invoked function. -func FaaSInvokedName(val string) attribute.KeyValue { - return FaaSInvokedNameKey.String(val) -} - -// FaaSInvokedRegion returns an attribute KeyValue conforming to the -// "faas.invoked_region" semantic conventions. It represents the cloud region -// of the invoked function. -func FaaSInvokedRegion(val string) attribute.KeyValue { - return FaaSInvokedRegionKey.String(val) -} - -// Attributes for Events represented using Log Records. -const ( - // EventNameKey is the attribute Key conforming to the "event.name" - // semantic conventions. It represents the identifies the class / type of - // event. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'browser.mouse.click', 'device.app.lifecycle' - // Note: Event names are subject to the same rules as [attribute - // names](https://github.com/open-telemetry/opentelemetry-specification/tree/v1.26.0/specification/common/attribute-naming.md). - // Notably, event names are namespaced to avoid collisions and provide a - // clean separation of semantics for events in separate domains like - // browser, mobile, and kubernetes. - EventNameKey = attribute.Key("event.name") -) - -// EventName returns an attribute KeyValue conforming to the "event.name" -// semantic conventions. It represents the identifies the class / type of -// event. -func EventName(val string) attribute.KeyValue { - return EventNameKey.String(val) -} - -// The attributes described in this section are rather generic. They may be -// used in any Log Record they apply to. -const ( - // LogRecordUIDKey is the attribute Key conforming to the "log.record.uid" - // semantic conventions. It represents a unique identifier for the Log - // Record. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '01ARZ3NDEKTSV4RRFFQ69G5FAV' - // Note: If an id is provided, other log records with the same id will be - // considered duplicates and can be removed safely. This means, that two - // distinguishable log records MUST have different values. - // The id MAY be an [Universally Unique Lexicographically Sortable - // Identifier (ULID)](https://github.com/ulid/spec), but other identifiers - // (e.g. UUID) may be used as needed. - LogRecordUIDKey = attribute.Key("log.record.uid") -) - -// LogRecordUID returns an attribute KeyValue conforming to the -// "log.record.uid" semantic conventions. It represents a unique identifier for -// the Log Record. -func LogRecordUID(val string) attribute.KeyValue { - return LogRecordUIDKey.String(val) -} - -// Describes Log attributes -const ( - // LogIostreamKey is the attribute Key conforming to the "log.iostream" - // semantic conventions. It represents the stream associated with the log. - // See below for a list of well-known values. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - LogIostreamKey = attribute.Key("log.iostream") -) - -var ( - // Logs from stdout stream - LogIostreamStdout = LogIostreamKey.String("stdout") - // Events from stderr stream - LogIostreamStderr = LogIostreamKey.String("stderr") -) - -// A file to which log was emitted. -const ( - // LogFileNameKey is the attribute Key conforming to the "log.file.name" - // semantic conventions. It represents the basename of the file. - // - // Type: string - // RequirementLevel: Recommended - // Stability: experimental - // Examples: 'audit.log' - LogFileNameKey = attribute.Key("log.file.name") - - // LogFileNameResolvedKey is the attribute Key conforming to the - // "log.file.name_resolved" semantic conventions. It represents the - // basename of the file, with symlinks resolved. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'uuid.log' - LogFileNameResolvedKey = attribute.Key("log.file.name_resolved") - - // LogFilePathKey is the attribute Key conforming to the "log.file.path" - // semantic conventions. It represents the full path to the file. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/var/log/mysql/audit.log' - LogFilePathKey = attribute.Key("log.file.path") - - // LogFilePathResolvedKey is the attribute Key conforming to the - // "log.file.path_resolved" semantic conventions. It represents the full - // path to the file, with symlinks resolved. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/var/lib/docker/uuid.log' - LogFilePathResolvedKey = attribute.Key("log.file.path_resolved") -) - -// LogFileName returns an attribute KeyValue conforming to the -// "log.file.name" semantic conventions. It represents the basename of the -// file. -func LogFileName(val string) attribute.KeyValue { - return LogFileNameKey.String(val) -} - -// LogFileNameResolved returns an attribute KeyValue conforming to the -// "log.file.name_resolved" semantic conventions. It represents the basename of -// the file, with symlinks resolved. -func LogFileNameResolved(val string) attribute.KeyValue { - return LogFileNameResolvedKey.String(val) -} - -// LogFilePath returns an attribute KeyValue conforming to the -// "log.file.path" semantic conventions. It represents the full path to the -// file. -func LogFilePath(val string) attribute.KeyValue { - return LogFilePathKey.String(val) -} - -// LogFilePathResolved returns an attribute KeyValue conforming to the -// "log.file.path_resolved" semantic conventions. It represents the full path -// to the file, with symlinks resolved. -func LogFilePathResolved(val string) attribute.KeyValue { - return LogFilePathResolvedKey.String(val) -} - -// Describes Database attributes -const ( - // PoolNameKey is the attribute Key conforming to the "pool.name" semantic - // conventions. It represents the name of the connection pool; unique - // within the instrumented application. In case the connection pool - // implementation doesn't provide a name, then the - // [db.connection_string](/docs/database/database-spans.md#connection-level-attributes) - // should be used - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'myDataSource' - PoolNameKey = attribute.Key("pool.name") - - // StateKey is the attribute Key conforming to the "state" semantic - // conventions. It represents the state of a connection in the pool - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - // Examples: 'idle' - StateKey = attribute.Key("state") -) - -var ( - // idle - StateIdle = StateKey.String("idle") - // used - StateUsed = StateKey.String("used") -) - -// PoolName returns an attribute KeyValue conforming to the "pool.name" -// semantic conventions. It represents the name of the connection pool; unique -// within the instrumented application. In case the connection pool -// implementation doesn't provide a name, then the -// [db.connection_string](/docs/database/database-spans.md#connection-level-attributes) -// should be used -func PoolName(val string) attribute.KeyValue { - return PoolNameKey.String(val) -} - -// ASP.NET Core attributes -const ( - // AspnetcoreDiagnosticsHandlerTypeKey is the attribute Key conforming to - // the "aspnetcore.diagnostics.handler.type" semantic conventions. It - // represents the full type name of the - // [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) - // implementation that handled the exception. - // - // Type: string - // RequirementLevel: ConditionallyRequired (if and only if the exception - // was handled by this handler.) - // Stability: experimental - // Examples: 'Contoso.MyHandler' - AspnetcoreDiagnosticsHandlerTypeKey = attribute.Key("aspnetcore.diagnostics.handler.type") - - // AspnetcoreRateLimitingPolicyKey is the attribute Key conforming to the - // "aspnetcore.rate_limiting.policy" semantic conventions. It represents - // the rate limiting policy name. - // - // Type: string - // RequirementLevel: ConditionallyRequired (if the matched endpoint for the - // request had a rate-limiting policy.) - // Stability: experimental - // Examples: 'fixed', 'sliding', 'token' - AspnetcoreRateLimitingPolicyKey = attribute.Key("aspnetcore.rate_limiting.policy") - - // AspnetcoreRateLimitingResultKey is the attribute Key conforming to the - // "aspnetcore.rate_limiting.result" semantic conventions. It represents - // the rate-limiting result, shows whether the lease was acquired or - // contains a rejection reason - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - // Examples: 'acquired', 'request_canceled' - AspnetcoreRateLimitingResultKey = attribute.Key("aspnetcore.rate_limiting.result") - - // AspnetcoreRequestIsUnhandledKey is the attribute Key conforming to the - // "aspnetcore.request.is_unhandled" semantic conventions. It represents - // the flag indicating if request was handled by the application pipeline. - // - // Type: boolean - // RequirementLevel: ConditionallyRequired (if and only if the request was - // not handled.) - // Stability: experimental - // Examples: True - AspnetcoreRequestIsUnhandledKey = attribute.Key("aspnetcore.request.is_unhandled") - - // AspnetcoreRoutingIsFallbackKey is the attribute Key conforming to the - // "aspnetcore.routing.is_fallback" semantic conventions. It represents a - // value that indicates whether the matched route is a fallback route. - // - // Type: boolean - // RequirementLevel: ConditionallyRequired (If and only if a route was - // successfully matched.) - // Stability: experimental - // Examples: True - AspnetcoreRoutingIsFallbackKey = attribute.Key("aspnetcore.routing.is_fallback") -) - -var ( - // Lease was acquired - AspnetcoreRateLimitingResultAcquired = AspnetcoreRateLimitingResultKey.String("acquired") - // Lease request was rejected by the endpoint limiter - AspnetcoreRateLimitingResultEndpointLimiter = AspnetcoreRateLimitingResultKey.String("endpoint_limiter") - // Lease request was rejected by the global limiter - AspnetcoreRateLimitingResultGlobalLimiter = AspnetcoreRateLimitingResultKey.String("global_limiter") - // Lease request was canceled - AspnetcoreRateLimitingResultRequestCanceled = AspnetcoreRateLimitingResultKey.String("request_canceled") -) - -// AspnetcoreDiagnosticsHandlerType returns an attribute KeyValue conforming -// to the "aspnetcore.diagnostics.handler.type" semantic conventions. It -// represents the full type name of the -// [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) -// implementation that handled the exception. -func AspnetcoreDiagnosticsHandlerType(val string) attribute.KeyValue { - return AspnetcoreDiagnosticsHandlerTypeKey.String(val) -} - -// AspnetcoreRateLimitingPolicy returns an attribute KeyValue conforming to -// the "aspnetcore.rate_limiting.policy" semantic conventions. It represents -// the rate limiting policy name. -func AspnetcoreRateLimitingPolicy(val string) attribute.KeyValue { - return AspnetcoreRateLimitingPolicyKey.String(val) -} - -// AspnetcoreRequestIsUnhandled returns an attribute KeyValue conforming to -// the "aspnetcore.request.is_unhandled" semantic conventions. It represents -// the flag indicating if request was handled by the application pipeline. -func AspnetcoreRequestIsUnhandled(val bool) attribute.KeyValue { - return AspnetcoreRequestIsUnhandledKey.Bool(val) -} - -// AspnetcoreRoutingIsFallback returns an attribute KeyValue conforming to -// the "aspnetcore.routing.is_fallback" semantic conventions. It represents a -// value that indicates whether the matched route is a fallback route. -func AspnetcoreRoutingIsFallback(val bool) attribute.KeyValue { - return AspnetcoreRoutingIsFallbackKey.Bool(val) -} - -// SignalR attributes -const ( - // SignalrConnectionStatusKey is the attribute Key conforming to the - // "signalr.connection.status" semantic conventions. It represents the - // signalR HTTP connection closure status. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'app_shutdown', 'timeout' - SignalrConnectionStatusKey = attribute.Key("signalr.connection.status") - - // SignalrTransportKey is the attribute Key conforming to the - // "signalr.transport" semantic conventions. It represents the [SignalR - // transport - // type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'web_sockets', 'long_polling' - SignalrTransportKey = attribute.Key("signalr.transport") -) - -var ( - // The connection was closed normally - SignalrConnectionStatusNormalClosure = SignalrConnectionStatusKey.String("normal_closure") - // The connection was closed due to a timeout - SignalrConnectionStatusTimeout = SignalrConnectionStatusKey.String("timeout") - // The connection was closed because the app is shutting down - SignalrConnectionStatusAppShutdown = SignalrConnectionStatusKey.String("app_shutdown") -) - -var ( - // ServerSentEvents protocol - SignalrTransportServerSentEvents = SignalrTransportKey.String("server_sent_events") - // LongPolling protocol - SignalrTransportLongPolling = SignalrTransportKey.String("long_polling") - // WebSockets protocol - SignalrTransportWebSockets = SignalrTransportKey.String("web_sockets") -) - -// Describes JVM buffer metric attributes. -const ( - // JvmBufferPoolNameKey is the attribute Key conforming to the - // "jvm.buffer.pool.name" semantic conventions. It represents the name of - // the buffer pool. - // - // Type: string - // RequirementLevel: Recommended - // Stability: experimental - // Examples: 'mapped', 'direct' - // Note: Pool names are generally obtained via - // [BufferPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/BufferPoolMXBean.html#getName()). - JvmBufferPoolNameKey = attribute.Key("jvm.buffer.pool.name") -) - -// JvmBufferPoolName returns an attribute KeyValue conforming to the -// "jvm.buffer.pool.name" semantic conventions. It represents the name of the -// buffer pool. -func JvmBufferPoolName(val string) attribute.KeyValue { - return JvmBufferPoolNameKey.String(val) -} - -// Describes JVM memory metric attributes. -const ( - // JvmMemoryPoolNameKey is the attribute Key conforming to the - // "jvm.memory.pool.name" semantic conventions. It represents the name of - // the memory pool. - // - // Type: string - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'G1 Old Gen', 'G1 Eden space', 'G1 Survivor Space' - // Note: Pool names are generally obtained via - // [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - JvmMemoryPoolNameKey = attribute.Key("jvm.memory.pool.name") - - // JvmMemoryTypeKey is the attribute Key conforming to the - // "jvm.memory.type" semantic conventions. It represents the type of - // memory. - // - // Type: Enum - // RequirementLevel: Recommended - // Stability: stable - // Examples: 'heap', 'non_heap' - JvmMemoryTypeKey = attribute.Key("jvm.memory.type") -) - -var ( - // Heap memory - JvmMemoryTypeHeap = JvmMemoryTypeKey.String("heap") - // Non-heap memory - JvmMemoryTypeNonHeap = JvmMemoryTypeKey.String("non_heap") -) - -// JvmMemoryPoolName returns an attribute KeyValue conforming to the -// "jvm.memory.pool.name" semantic conventions. It represents the name of the -// memory pool. -func JvmMemoryPoolName(val string) attribute.KeyValue { - return JvmMemoryPoolNameKey.String(val) -} - -// Describes System metric attributes -const ( - // SystemDeviceKey is the attribute Key conforming to the "system.device" - // semantic conventions. It represents the device identifier - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '(identifier)' - SystemDeviceKey = attribute.Key("system.device") -) - -// SystemDevice returns an attribute KeyValue conforming to the -// "system.device" semantic conventions. It represents the device identifier -func SystemDevice(val string) attribute.KeyValue { - return SystemDeviceKey.String(val) -} - -// Describes System CPU metric attributes -const ( - // SystemCPULogicalNumberKey is the attribute Key conforming to the - // "system.cpu.logical_number" semantic conventions. It represents the - // logical CPU number [0..n-1] - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1 - SystemCPULogicalNumberKey = attribute.Key("system.cpu.logical_number") - - // SystemCPUStateKey is the attribute Key conforming to the - // "system.cpu.state" semantic conventions. It represents the state of the - // CPU - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'idle', 'interrupt' - SystemCPUStateKey = attribute.Key("system.cpu.state") -) - -var ( - // user - SystemCPUStateUser = SystemCPUStateKey.String("user") - // system - SystemCPUStateSystem = SystemCPUStateKey.String("system") - // nice - SystemCPUStateNice = SystemCPUStateKey.String("nice") - // idle - SystemCPUStateIdle = SystemCPUStateKey.String("idle") - // iowait - SystemCPUStateIowait = SystemCPUStateKey.String("iowait") - // interrupt - SystemCPUStateInterrupt = SystemCPUStateKey.String("interrupt") - // steal - SystemCPUStateSteal = SystemCPUStateKey.String("steal") -) - -// SystemCPULogicalNumber returns an attribute KeyValue conforming to the -// "system.cpu.logical_number" semantic conventions. It represents the logical -// CPU number [0..n-1] -func SystemCPULogicalNumber(val int) attribute.KeyValue { - return SystemCPULogicalNumberKey.Int(val) -} - -// Describes System Memory metric attributes -const ( - // SystemMemoryStateKey is the attribute Key conforming to the - // "system.memory.state" semantic conventions. It represents the memory - // state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'free', 'cached' - SystemMemoryStateKey = attribute.Key("system.memory.state") -) - -var ( - // used - SystemMemoryStateUsed = SystemMemoryStateKey.String("used") - // free - SystemMemoryStateFree = SystemMemoryStateKey.String("free") - // shared - SystemMemoryStateShared = SystemMemoryStateKey.String("shared") - // buffers - SystemMemoryStateBuffers = SystemMemoryStateKey.String("buffers") - // cached - SystemMemoryStateCached = SystemMemoryStateKey.String("cached") -) - -// Describes System Memory Paging metric attributes -const ( - // SystemPagingDirectionKey is the attribute Key conforming to the - // "system.paging.direction" semantic conventions. It represents the paging - // access direction - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'in' - SystemPagingDirectionKey = attribute.Key("system.paging.direction") - - // SystemPagingStateKey is the attribute Key conforming to the - // "system.paging.state" semantic conventions. It represents the memory - // paging state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'free' - SystemPagingStateKey = attribute.Key("system.paging.state") - - // SystemPagingTypeKey is the attribute Key conforming to the - // "system.paging.type" semantic conventions. It represents the memory - // paging type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'minor' - SystemPagingTypeKey = attribute.Key("system.paging.type") -) - -var ( - // in - SystemPagingDirectionIn = SystemPagingDirectionKey.String("in") - // out - SystemPagingDirectionOut = SystemPagingDirectionKey.String("out") -) - -var ( - // used - SystemPagingStateUsed = SystemPagingStateKey.String("used") - // free - SystemPagingStateFree = SystemPagingStateKey.String("free") -) - -var ( - // major - SystemPagingTypeMajor = SystemPagingTypeKey.String("major") - // minor - SystemPagingTypeMinor = SystemPagingTypeKey.String("minor") -) - -// Describes Filesystem metric attributes -const ( - // SystemFilesystemModeKey is the attribute Key conforming to the - // "system.filesystem.mode" semantic conventions. It represents the - // filesystem mode - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'rw, ro' - SystemFilesystemModeKey = attribute.Key("system.filesystem.mode") - - // SystemFilesystemMountpointKey is the attribute Key conforming to the - // "system.filesystem.mountpoint" semantic conventions. It represents the - // filesystem mount path - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/mnt/data' - SystemFilesystemMountpointKey = attribute.Key("system.filesystem.mountpoint") - - // SystemFilesystemStateKey is the attribute Key conforming to the - // "system.filesystem.state" semantic conventions. It represents the - // filesystem state - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'used' - SystemFilesystemStateKey = attribute.Key("system.filesystem.state") - - // SystemFilesystemTypeKey is the attribute Key conforming to the - // "system.filesystem.type" semantic conventions. It represents the - // filesystem type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ext4' - SystemFilesystemTypeKey = attribute.Key("system.filesystem.type") -) - -var ( - // used - SystemFilesystemStateUsed = SystemFilesystemStateKey.String("used") - // free - SystemFilesystemStateFree = SystemFilesystemStateKey.String("free") - // reserved - SystemFilesystemStateReserved = SystemFilesystemStateKey.String("reserved") -) - -var ( - // fat32 - SystemFilesystemTypeFat32 = SystemFilesystemTypeKey.String("fat32") - // exfat - SystemFilesystemTypeExfat = SystemFilesystemTypeKey.String("exfat") - // ntfs - SystemFilesystemTypeNtfs = SystemFilesystemTypeKey.String("ntfs") - // refs - SystemFilesystemTypeRefs = SystemFilesystemTypeKey.String("refs") - // hfsplus - SystemFilesystemTypeHfsplus = SystemFilesystemTypeKey.String("hfsplus") - // ext4 - SystemFilesystemTypeExt4 = SystemFilesystemTypeKey.String("ext4") -) - -// SystemFilesystemMode returns an attribute KeyValue conforming to the -// "system.filesystem.mode" semantic conventions. It represents the filesystem -// mode -func SystemFilesystemMode(val string) attribute.KeyValue { - return SystemFilesystemModeKey.String(val) -} - -// SystemFilesystemMountpoint returns an attribute KeyValue conforming to -// the "system.filesystem.mountpoint" semantic conventions. It represents the -// filesystem mount path -func SystemFilesystemMountpoint(val string) attribute.KeyValue { - return SystemFilesystemMountpointKey.String(val) -} - -// Describes Network metric attributes -const ( - // SystemNetworkStateKey is the attribute Key conforming to the - // "system.network.state" semantic conventions. It represents a stateless - // protocol MUST NOT set this attribute - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'close_wait' - SystemNetworkStateKey = attribute.Key("system.network.state") -) - -var ( - // close - SystemNetworkStateClose = SystemNetworkStateKey.String("close") - // close_wait - SystemNetworkStateCloseWait = SystemNetworkStateKey.String("close_wait") - // closing - SystemNetworkStateClosing = SystemNetworkStateKey.String("closing") - // delete - SystemNetworkStateDelete = SystemNetworkStateKey.String("delete") - // established - SystemNetworkStateEstablished = SystemNetworkStateKey.String("established") - // fin_wait_1 - SystemNetworkStateFinWait1 = SystemNetworkStateKey.String("fin_wait_1") - // fin_wait_2 - SystemNetworkStateFinWait2 = SystemNetworkStateKey.String("fin_wait_2") - // last_ack - SystemNetworkStateLastAck = SystemNetworkStateKey.String("last_ack") - // listen - SystemNetworkStateListen = SystemNetworkStateKey.String("listen") - // syn_recv - SystemNetworkStateSynRecv = SystemNetworkStateKey.String("syn_recv") - // syn_sent - SystemNetworkStateSynSent = SystemNetworkStateKey.String("syn_sent") - // time_wait - SystemNetworkStateTimeWait = SystemNetworkStateKey.String("time_wait") -) - -// Describes System Process metric attributes -const ( - // SystemProcessesStatusKey is the attribute Key conforming to the - // "system.processes.status" semantic conventions. It represents the - // process state, e.g., [Linux Process State - // Codes](https://man7.org/linux/man-pages/man1/ps.1.html#PROCESS_STATE_CODES) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'running' - SystemProcessesStatusKey = attribute.Key("system.processes.status") -) - -var ( - // running - SystemProcessesStatusRunning = SystemProcessesStatusKey.String("running") - // sleeping - SystemProcessesStatusSleeping = SystemProcessesStatusKey.String("sleeping") - // stopped - SystemProcessesStatusStopped = SystemProcessesStatusKey.String("stopped") - // defunct - SystemProcessesStatusDefunct = SystemProcessesStatusKey.String("defunct") -) - -// These attributes may be used to describe the client in a connection-based -// network interaction where there is one side that initiates the connection -// (the client is the side that initiates the connection). This covers all TCP -// network interactions since TCP is connection-based and one side initiates -// the connection (an exception is made for peer-to-peer communication over TCP -// where the "user-facing" surface of the protocol / API doesn't expose a clear -// notion of client and server). This also covers UDP network interactions -// where one side initiates the interaction, e.g. QUIC (HTTP/3) and DNS. -const ( - // ClientAddressKey is the attribute Key conforming to the "client.address" - // semantic conventions. It represents the client address - domain name if - // available without reverse DNS lookup; otherwise, IP address or Unix - // domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'client.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the server side, and when communicating through - // an intermediary, `client.address` SHOULD represent the client address - // behind any intermediaries, for example proxies, if it's available. - ClientAddressKey = attribute.Key("client.address") - - // ClientPortKey is the attribute Key conforming to the "client.port" - // semantic conventions. It represents the client port number. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - // Note: When observed from the server side, and when communicating through - // an intermediary, `client.port` SHOULD represent the client port behind - // any intermediaries, for example proxies, if it's available. - ClientPortKey = attribute.Key("client.port") -) - -// ClientAddress returns an attribute KeyValue conforming to the -// "client.address" semantic conventions. It represents the client address - -// domain name if available without reverse DNS lookup; otherwise, IP address -// or Unix domain socket name. -func ClientAddress(val string) attribute.KeyValue { - return ClientAddressKey.String(val) -} - -// ClientPort returns an attribute KeyValue conforming to the "client.port" -// semantic conventions. It represents the client port number. -func ClientPort(val int) attribute.KeyValue { - return ClientPortKey.Int(val) -} - -// The attributes used to describe telemetry in the context of databases. -const ( - // DBCassandraConsistencyLevelKey is the attribute Key conforming to the - // "db.cassandra.consistency_level" semantic conventions. It represents the - // consistency level of the query. Based on consistency values from - // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") - - // DBCassandraCoordinatorDCKey is the attribute Key conforming to the - // "db.cassandra.coordinator.dc" semantic conventions. It represents the - // data center of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-west-2' - DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") - - // DBCassandraCoordinatorIDKey is the attribute Key conforming to the - // "db.cassandra.coordinator.id" semantic conventions. It represents the ID - // of the coordinating node for a query. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' - DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") - - // DBCassandraIdempotenceKey is the attribute Key conforming to the - // "db.cassandra.idempotence" semantic conventions. It represents the - // whether or not the query is idempotent. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") - - // DBCassandraPageSizeKey is the attribute Key conforming to the - // "db.cassandra.page_size" semantic conventions. It represents the fetch - // size used for paging, i.e. how many rows will be returned at once. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 5000 - DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") - - // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming - // to the "db.cassandra.speculative_execution_count" semantic conventions. - // It represents the number of times a query was speculatively executed. - // Not set or `0` if the query was not executed speculatively. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 2 - DBCassandraSpeculativeExecutionCountKey = attribute.Key("db.cassandra.speculative_execution_count") - - // DBCassandraTableKey is the attribute Key conforming to the - // "db.cassandra.table" semantic conventions. It represents the name of the - // primary Cassandra table that the operation is acting upon, including the - // keyspace name (if applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mytable' - // Note: This mirrors the db.sql.table attribute but references cassandra - // rather than sql. It is not recommended to attempt any client-side - // parsing of `db.statement` just to get this property, but it should be - // set if it is provided by the library being instrumented. If the - // operation is acting upon an anonymous table, or more than one table, - // this value MUST NOT be set. - DBCassandraTableKey = attribute.Key("db.cassandra.table") - - // DBConnectionStringKey is the attribute Key conforming to the - // "db.connection_string" semantic conventions. It represents the - // connection string used to connect to the database. It is recommended to - // remove embedded credentials. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Server=(localdb)\\v11.0;Integrated Security=true;' - DBConnectionStringKey = attribute.Key("db.connection_string") - - // DBCosmosDBClientIDKey is the attribute Key conforming to the - // "db.cosmosdb.client_id" semantic conventions. It represents the unique - // Cosmos client instance id. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '3ba4827d-4422-483f-b59f-85b74211c11d' - DBCosmosDBClientIDKey = attribute.Key("db.cosmosdb.client_id") - - // DBCosmosDBConnectionModeKey is the attribute Key conforming to the - // "db.cosmosdb.connection_mode" semantic conventions. It represents the - // cosmos client connection mode. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBConnectionModeKey = attribute.Key("db.cosmosdb.connection_mode") - - // DBCosmosDBContainerKey is the attribute Key conforming to the - // "db.cosmosdb.container" semantic conventions. It represents the cosmos - // DB container name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'anystring' - DBCosmosDBContainerKey = attribute.Key("db.cosmosdb.container") - - // DBCosmosDBOperationTypeKey is the attribute Key conforming to the - // "db.cosmosdb.operation_type" semantic conventions. It represents the - // cosmosDB Operation Type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBOperationTypeKey = attribute.Key("db.cosmosdb.operation_type") - - // DBCosmosDBRequestChargeKey is the attribute Key conforming to the - // "db.cosmosdb.request_charge" semantic conventions. It represents the rU - // consumed for that operation - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 46.18, 1.0 - DBCosmosDBRequestChargeKey = attribute.Key("db.cosmosdb.request_charge") - - // DBCosmosDBRequestContentLengthKey is the attribute Key conforming to the - // "db.cosmosdb.request_content_length" semantic conventions. It represents - // the request payload size in bytes - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - DBCosmosDBRequestContentLengthKey = attribute.Key("db.cosmosdb.request_content_length") - - // DBCosmosDBStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.status_code" semantic conventions. It represents the cosmos - // DB status code. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 200, 201 - DBCosmosDBStatusCodeKey = attribute.Key("db.cosmosdb.status_code") - - // DBCosmosDBSubStatusCodeKey is the attribute Key conforming to the - // "db.cosmosdb.sub_status_code" semantic conventions. It represents the - // cosmos DB sub status code. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1000, 1002 - DBCosmosDBSubStatusCodeKey = attribute.Key("db.cosmosdb.sub_status_code") - - // DBElasticsearchClusterNameKey is the attribute Key conforming to the - // "db.elasticsearch.cluster.name" semantic conventions. It represents the - // represents the identifier of an Elasticsearch cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'e9106fc68e3044f0b1475b04bf4ffd5f' - DBElasticsearchClusterNameKey = attribute.Key("db.elasticsearch.cluster.name") - - // DBElasticsearchNodeNameKey is the attribute Key conforming to the - // "db.elasticsearch.node.name" semantic conventions. It represents the - // represents the human-readable identifier of the node/instance to which a - // request was routed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'instance-0000000001' - DBElasticsearchNodeNameKey = attribute.Key("db.elasticsearch.node.name") - - // DBInstanceIDKey is the attribute Key conforming to the "db.instance.id" - // semantic conventions. It represents an identifier (address, unique name, - // or any other identifier) of the database instance that is executing - // queries or mutations on the current connection. This is useful in cases - // where the database is running in a clustered environment and the - // instrumentation is able to record the node executing the query. The - // client may obtain this value in databases like MySQL using queries like - // `select @@hostname`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mysql-e26b99z.example.com' - DBInstanceIDKey = attribute.Key("db.instance.id") - - // DBJDBCDriverClassnameKey is the attribute Key conforming to the - // "db.jdbc.driver_classname" semantic conventions. It represents the - // fully-qualified class name of the [Java Database Connectivity - // (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) - // driver used to connect. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'org.postgresql.Driver', - // 'com.microsoft.sqlserver.jdbc.SQLServerDriver' - DBJDBCDriverClassnameKey = attribute.Key("db.jdbc.driver_classname") - - // DBMongoDBCollectionKey is the attribute Key conforming to the - // "db.mongodb.collection" semantic conventions. It represents the MongoDB - // collection being accessed within the database stated in `db.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'customers', 'products' - DBMongoDBCollectionKey = attribute.Key("db.mongodb.collection") - - // DBMSSQLInstanceNameKey is the attribute Key conforming to the - // "db.mssql.instance_name" semantic conventions. It represents the - // Microsoft SQL Server [instance - // name](https://docs.microsoft.com/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) - // connecting to. This name is used to determine the port of a named - // instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MSSQLSERVER' - // Note: If setting a `db.mssql.instance_name`, `server.port` is no longer - // required (but still recommended if non-standard). - DBMSSQLInstanceNameKey = attribute.Key("db.mssql.instance_name") - - // DBNameKey is the attribute Key conforming to the "db.name" semantic - // conventions. It represents the this attribute is used to report the name - // of the database being accessed. For commands that switch the database, - // this should be set to the target database (even if the command fails). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'customers', 'main' - // Note: In some SQL databases, the database name to be used is called - // "schema name". In case there are multiple layers that could be - // considered for database name (e.g. Oracle instance name and schema - // name), the database name to be used is the more specific layer (e.g. - // Oracle schema name). - DBNameKey = attribute.Key("db.name") - - // DBOperationKey is the attribute Key conforming to the "db.operation" - // semantic conventions. It represents the name of the operation being - // executed, e.g. the [MongoDB command - // name](https://docs.mongodb.com/manual/reference/command/#database-operations) - // such as `findAndModify`, or the SQL keyword. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'findAndModify', 'HMSET', 'SELECT' - // Note: When setting this to an SQL keyword, it is not recommended to - // attempt any client-side parsing of `db.statement` just to get this - // property, but it should be set if the operation name is provided by the - // library being instrumented. If the SQL statement has an ambiguous - // operation, or performs more than one operation, this value may be - // omitted. - DBOperationKey = attribute.Key("db.operation") - - // DBRedisDBIndexKey is the attribute Key conforming to the - // "db.redis.database_index" semantic conventions. It represents the index - // of the database being accessed as used in the [`SELECT` - // command](https://redis.io/commands/select), provided as an integer. To - // be used instead of the generic `db.name` attribute. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 1, 15 - DBRedisDBIndexKey = attribute.Key("db.redis.database_index") - - // DBSQLTableKey is the attribute Key conforming to the "db.sql.table" - // semantic conventions. It represents the name of the primary table that - // the operation is acting upon, including the database name (if - // applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'public.users', 'customers' - // Note: It is not recommended to attempt any client-side parsing of - // `db.statement` just to get this property, but it should be set if it is - // provided by the library being instrumented. If the operation is acting - // upon an anonymous table, or more than one table, this value MUST NOT be - // set. - DBSQLTableKey = attribute.Key("db.sql.table") - - // DBStatementKey is the attribute Key conforming to the "db.statement" - // semantic conventions. It represents the database statement being - // executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'SELECT * FROM wuser_table', 'SET mykey "WuValue"' - DBStatementKey = attribute.Key("db.statement") - - // DBSystemKey is the attribute Key conforming to the "db.system" semantic - // conventions. It represents an identifier for the database management - // system (DBMS) product being used. See below for a list of well-known - // identifiers. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - DBSystemKey = attribute.Key("db.system") - - // DBUserKey is the attribute Key conforming to the "db.user" semantic - // conventions. It represents the username for accessing the database. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'readonly_user', 'reporting_user' - DBUserKey = attribute.Key("db.user") -) - -var ( - // all - DBCassandraConsistencyLevelAll = DBCassandraConsistencyLevelKey.String("all") - // each_quorum - DBCassandraConsistencyLevelEachQuorum = DBCassandraConsistencyLevelKey.String("each_quorum") - // quorum - DBCassandraConsistencyLevelQuorum = DBCassandraConsistencyLevelKey.String("quorum") - // local_quorum - DBCassandraConsistencyLevelLocalQuorum = DBCassandraConsistencyLevelKey.String("local_quorum") - // one - DBCassandraConsistencyLevelOne = DBCassandraConsistencyLevelKey.String("one") - // two - DBCassandraConsistencyLevelTwo = DBCassandraConsistencyLevelKey.String("two") - // three - DBCassandraConsistencyLevelThree = DBCassandraConsistencyLevelKey.String("three") - // local_one - DBCassandraConsistencyLevelLocalOne = DBCassandraConsistencyLevelKey.String("local_one") - // any - DBCassandraConsistencyLevelAny = DBCassandraConsistencyLevelKey.String("any") - // serial - DBCassandraConsistencyLevelSerial = DBCassandraConsistencyLevelKey.String("serial") - // local_serial - DBCassandraConsistencyLevelLocalSerial = DBCassandraConsistencyLevelKey.String("local_serial") -) - -var ( - // Gateway (HTTP) connections mode - DBCosmosDBConnectionModeGateway = DBCosmosDBConnectionModeKey.String("gateway") - // Direct connection - DBCosmosDBConnectionModeDirect = DBCosmosDBConnectionModeKey.String("direct") -) - -var ( - // invalid - DBCosmosDBOperationTypeInvalid = DBCosmosDBOperationTypeKey.String("Invalid") - // create - DBCosmosDBOperationTypeCreate = DBCosmosDBOperationTypeKey.String("Create") - // patch - DBCosmosDBOperationTypePatch = DBCosmosDBOperationTypeKey.String("Patch") - // read - DBCosmosDBOperationTypeRead = DBCosmosDBOperationTypeKey.String("Read") - // read_feed - DBCosmosDBOperationTypeReadFeed = DBCosmosDBOperationTypeKey.String("ReadFeed") - // delete - DBCosmosDBOperationTypeDelete = DBCosmosDBOperationTypeKey.String("Delete") - // replace - DBCosmosDBOperationTypeReplace = DBCosmosDBOperationTypeKey.String("Replace") - // execute - DBCosmosDBOperationTypeExecute = DBCosmosDBOperationTypeKey.String("Execute") - // query - DBCosmosDBOperationTypeQuery = DBCosmosDBOperationTypeKey.String("Query") - // head - DBCosmosDBOperationTypeHead = DBCosmosDBOperationTypeKey.String("Head") - // head_feed - DBCosmosDBOperationTypeHeadFeed = DBCosmosDBOperationTypeKey.String("HeadFeed") - // upsert - DBCosmosDBOperationTypeUpsert = DBCosmosDBOperationTypeKey.String("Upsert") - // batch - DBCosmosDBOperationTypeBatch = DBCosmosDBOperationTypeKey.String("Batch") - // query_plan - DBCosmosDBOperationTypeQueryPlan = DBCosmosDBOperationTypeKey.String("QueryPlan") - // execute_javascript - DBCosmosDBOperationTypeExecuteJavascript = DBCosmosDBOperationTypeKey.String("ExecuteJavaScript") -) - -var ( - // Some other SQL database. Fallback only. See notes - DBSystemOtherSQL = DBSystemKey.String("other_sql") - // Microsoft SQL Server - DBSystemMSSQL = DBSystemKey.String("mssql") - // Microsoft SQL Server Compact - DBSystemMssqlcompact = DBSystemKey.String("mssqlcompact") - // MySQL - DBSystemMySQL = DBSystemKey.String("mysql") - // Oracle Database - DBSystemOracle = DBSystemKey.String("oracle") - // IBM DB2 - DBSystemDB2 = DBSystemKey.String("db2") - // PostgreSQL - DBSystemPostgreSQL = DBSystemKey.String("postgresql") - // Amazon Redshift - DBSystemRedshift = DBSystemKey.String("redshift") - // Apache Hive - DBSystemHive = DBSystemKey.String("hive") - // Cloudscape - DBSystemCloudscape = DBSystemKey.String("cloudscape") - // HyperSQL DataBase - DBSystemHSQLDB = DBSystemKey.String("hsqldb") - // Progress Database - DBSystemProgress = DBSystemKey.String("progress") - // SAP MaxDB - DBSystemMaxDB = DBSystemKey.String("maxdb") - // SAP HANA - DBSystemHanaDB = DBSystemKey.String("hanadb") - // Ingres - DBSystemIngres = DBSystemKey.String("ingres") - // FirstSQL - DBSystemFirstSQL = DBSystemKey.String("firstsql") - // EnterpriseDB - DBSystemEDB = DBSystemKey.String("edb") - // InterSystems Caché - DBSystemCache = DBSystemKey.String("cache") - // Adabas (Adaptable Database System) - DBSystemAdabas = DBSystemKey.String("adabas") - // Firebird - DBSystemFirebird = DBSystemKey.String("firebird") - // Apache Derby - DBSystemDerby = DBSystemKey.String("derby") - // FileMaker - DBSystemFilemaker = DBSystemKey.String("filemaker") - // Informix - DBSystemInformix = DBSystemKey.String("informix") - // InstantDB - DBSystemInstantDB = DBSystemKey.String("instantdb") - // InterBase - DBSystemInterbase = DBSystemKey.String("interbase") - // MariaDB - DBSystemMariaDB = DBSystemKey.String("mariadb") - // Netezza - DBSystemNetezza = DBSystemKey.String("netezza") - // Pervasive PSQL - DBSystemPervasive = DBSystemKey.String("pervasive") - // PointBase - DBSystemPointbase = DBSystemKey.String("pointbase") - // SQLite - DBSystemSqlite = DBSystemKey.String("sqlite") - // Sybase - DBSystemSybase = DBSystemKey.String("sybase") - // Teradata - DBSystemTeradata = DBSystemKey.String("teradata") - // Vertica - DBSystemVertica = DBSystemKey.String("vertica") - // H2 - DBSystemH2 = DBSystemKey.String("h2") - // ColdFusion IMQ - DBSystemColdfusion = DBSystemKey.String("coldfusion") - // Apache Cassandra - DBSystemCassandra = DBSystemKey.String("cassandra") - // Apache HBase - DBSystemHBase = DBSystemKey.String("hbase") - // MongoDB - DBSystemMongoDB = DBSystemKey.String("mongodb") - // Redis - DBSystemRedis = DBSystemKey.String("redis") - // Couchbase - DBSystemCouchbase = DBSystemKey.String("couchbase") - // CouchDB - DBSystemCouchDB = DBSystemKey.String("couchdb") - // Microsoft Azure Cosmos DB - DBSystemCosmosDB = DBSystemKey.String("cosmosdb") - // Amazon DynamoDB - DBSystemDynamoDB = DBSystemKey.String("dynamodb") - // Neo4j - DBSystemNeo4j = DBSystemKey.String("neo4j") - // Apache Geode - DBSystemGeode = DBSystemKey.String("geode") - // Elasticsearch - DBSystemElasticsearch = DBSystemKey.String("elasticsearch") - // Memcached - DBSystemMemcached = DBSystemKey.String("memcached") - // CockroachDB - DBSystemCockroachdb = DBSystemKey.String("cockroachdb") - // OpenSearch - DBSystemOpensearch = DBSystemKey.String("opensearch") - // ClickHouse - DBSystemClickhouse = DBSystemKey.String("clickhouse") - // Cloud Spanner - DBSystemSpanner = DBSystemKey.String("spanner") - // Trino - DBSystemTrino = DBSystemKey.String("trino") -) - -// DBCassandraCoordinatorDC returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.dc" semantic conventions. It represents the data -// center of the coordinating node for a query. -func DBCassandraCoordinatorDC(val string) attribute.KeyValue { - return DBCassandraCoordinatorDCKey.String(val) -} - -// DBCassandraCoordinatorID returns an attribute KeyValue conforming to the -// "db.cassandra.coordinator.id" semantic conventions. It represents the ID of -// the coordinating node for a query. -func DBCassandraCoordinatorID(val string) attribute.KeyValue { - return DBCassandraCoordinatorIDKey.String(val) -} - -// DBCassandraIdempotence returns an attribute KeyValue conforming to the -// "db.cassandra.idempotence" semantic conventions. It represents the whether -// or not the query is idempotent. -func DBCassandraIdempotence(val bool) attribute.KeyValue { - return DBCassandraIdempotenceKey.Bool(val) -} - -// DBCassandraPageSize returns an attribute KeyValue conforming to the -// "db.cassandra.page_size" semantic conventions. It represents the fetch size -// used for paging, i.e. how many rows will be returned at once. -func DBCassandraPageSize(val int) attribute.KeyValue { - return DBCassandraPageSizeKey.Int(val) -} - -// DBCassandraSpeculativeExecutionCount returns an attribute KeyValue -// conforming to the "db.cassandra.speculative_execution_count" semantic -// conventions. It represents the number of times a query was speculatively -// executed. Not set or `0` if the query was not executed speculatively. -func DBCassandraSpeculativeExecutionCount(val int) attribute.KeyValue { - return DBCassandraSpeculativeExecutionCountKey.Int(val) -} - -// DBCassandraTable returns an attribute KeyValue conforming to the -// "db.cassandra.table" semantic conventions. It represents the name of the -// primary Cassandra table that the operation is acting upon, including the -// keyspace name (if applicable). -func DBCassandraTable(val string) attribute.KeyValue { - return DBCassandraTableKey.String(val) -} - -// DBConnectionString returns an attribute KeyValue conforming to the -// "db.connection_string" semantic conventions. It represents the connection -// string used to connect to the database. It is recommended to remove embedded -// credentials. -func DBConnectionString(val string) attribute.KeyValue { - return DBConnectionStringKey.String(val) -} - -// DBCosmosDBClientID returns an attribute KeyValue conforming to the -// "db.cosmosdb.client_id" semantic conventions. It represents the unique -// Cosmos client instance id. -func DBCosmosDBClientID(val string) attribute.KeyValue { - return DBCosmosDBClientIDKey.String(val) -} - -// DBCosmosDBContainer returns an attribute KeyValue conforming to the -// "db.cosmosdb.container" semantic conventions. It represents the cosmos DB -// container name. -func DBCosmosDBContainer(val string) attribute.KeyValue { - return DBCosmosDBContainerKey.String(val) -} - -// DBCosmosDBRequestCharge returns an attribute KeyValue conforming to the -// "db.cosmosdb.request_charge" semantic conventions. It represents the rU -// consumed for that operation -func DBCosmosDBRequestCharge(val float64) attribute.KeyValue { - return DBCosmosDBRequestChargeKey.Float64(val) -} - -// DBCosmosDBRequestContentLength returns an attribute KeyValue conforming -// to the "db.cosmosdb.request_content_length" semantic conventions. It -// represents the request payload size in bytes -func DBCosmosDBRequestContentLength(val int) attribute.KeyValue { - return DBCosmosDBRequestContentLengthKey.Int(val) -} - -// DBCosmosDBStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.status_code" semantic conventions. It represents the cosmos DB -// status code. -func DBCosmosDBStatusCode(val int) attribute.KeyValue { - return DBCosmosDBStatusCodeKey.Int(val) -} - -// DBCosmosDBSubStatusCode returns an attribute KeyValue conforming to the -// "db.cosmosdb.sub_status_code" semantic conventions. It represents the cosmos -// DB sub status code. -func DBCosmosDBSubStatusCode(val int) attribute.KeyValue { - return DBCosmosDBSubStatusCodeKey.Int(val) -} - -// DBElasticsearchClusterName returns an attribute KeyValue conforming to -// the "db.elasticsearch.cluster.name" semantic conventions. It represents the -// represents the identifier of an Elasticsearch cluster. -func DBElasticsearchClusterName(val string) attribute.KeyValue { - return DBElasticsearchClusterNameKey.String(val) -} - -// DBElasticsearchNodeName returns an attribute KeyValue conforming to the -// "db.elasticsearch.node.name" semantic conventions. It represents the -// represents the human-readable identifier of the node/instance to which a -// request was routed. -func DBElasticsearchNodeName(val string) attribute.KeyValue { - return DBElasticsearchNodeNameKey.String(val) -} - -// DBInstanceID returns an attribute KeyValue conforming to the -// "db.instance.id" semantic conventions. It represents an identifier (address, -// unique name, or any other identifier) of the database instance that is -// executing queries or mutations on the current connection. This is useful in -// cases where the database is running in a clustered environment and the -// instrumentation is able to record the node executing the query. The client -// may obtain this value in databases like MySQL using queries like `select -// @@hostname`. -func DBInstanceID(val string) attribute.KeyValue { - return DBInstanceIDKey.String(val) -} - -// DBJDBCDriverClassname returns an attribute KeyValue conforming to the -// "db.jdbc.driver_classname" semantic conventions. It represents the -// fully-qualified class name of the [Java Database Connectivity -// (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver -// used to connect. -func DBJDBCDriverClassname(val string) attribute.KeyValue { - return DBJDBCDriverClassnameKey.String(val) -} - -// DBMongoDBCollection returns an attribute KeyValue conforming to the -// "db.mongodb.collection" semantic conventions. It represents the MongoDB -// collection being accessed within the database stated in `db.name`. -func DBMongoDBCollection(val string) attribute.KeyValue { - return DBMongoDBCollectionKey.String(val) -} - -// DBMSSQLInstanceName returns an attribute KeyValue conforming to the -// "db.mssql.instance_name" semantic conventions. It represents the Microsoft -// SQL Server [instance -// name](https://docs.microsoft.com/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) -// connecting to. This name is used to determine the port of a named instance. -func DBMSSQLInstanceName(val string) attribute.KeyValue { - return DBMSSQLInstanceNameKey.String(val) -} - -// DBName returns an attribute KeyValue conforming to the "db.name" semantic -// conventions. It represents the this attribute is used to report the name of -// the database being accessed. For commands that switch the database, this -// should be set to the target database (even if the command fails). -func DBName(val string) attribute.KeyValue { - return DBNameKey.String(val) -} - -// DBOperation returns an attribute KeyValue conforming to the -// "db.operation" semantic conventions. It represents the name of the operation -// being executed, e.g. the [MongoDB command -// name](https://docs.mongodb.com/manual/reference/command/#database-operations) -// such as `findAndModify`, or the SQL keyword. -func DBOperation(val string) attribute.KeyValue { - return DBOperationKey.String(val) -} - -// DBRedisDBIndex returns an attribute KeyValue conforming to the -// "db.redis.database_index" semantic conventions. It represents the index of -// the database being accessed as used in the [`SELECT` -// command](https://redis.io/commands/select), provided as an integer. To be -// used instead of the generic `db.name` attribute. -func DBRedisDBIndex(val int) attribute.KeyValue { - return DBRedisDBIndexKey.Int(val) -} - -// DBSQLTable returns an attribute KeyValue conforming to the "db.sql.table" -// semantic conventions. It represents the name of the primary table that the -// operation is acting upon, including the database name (if applicable). -func DBSQLTable(val string) attribute.KeyValue { - return DBSQLTableKey.String(val) -} - -// DBStatement returns an attribute KeyValue conforming to the -// "db.statement" semantic conventions. It represents the database statement -// being executed. -func DBStatement(val string) attribute.KeyValue { - return DBStatementKey.String(val) -} - -// DBUser returns an attribute KeyValue conforming to the "db.user" semantic -// conventions. It represents the username for accessing the database. -func DBUser(val string) attribute.KeyValue { - return DBUserKey.String(val) -} - -// Describes deprecated HTTP attributes. -const ( - // HTTPFlavorKey is the attribute Key conforming to the "http.flavor" - // semantic conventions. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: deprecated - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorKey = attribute.Key("http.flavor") - - // HTTPMethodKey is the attribute Key conforming to the "http.method" - // semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'GET', 'POST', 'HEAD' - // Deprecated: use `http.request.method` instead. - HTTPMethodKey = attribute.Key("http.method") - - // HTTPRequestContentLengthKey is the attribute Key conforming to the - // "http.request_content_length" semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 3495 - // Deprecated: use `http.request.header.content-length` instead. - HTTPRequestContentLengthKey = attribute.Key("http.request_content_length") - - // HTTPResponseContentLengthKey is the attribute Key conforming to the - // "http.response_content_length" semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 3495 - // Deprecated: use `http.response.header.content-length` instead. - HTTPResponseContentLengthKey = attribute.Key("http.response_content_length") - - // HTTPSchemeKey is the attribute Key conforming to the "http.scheme" - // semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'http', 'https' - // Deprecated: use `url.scheme` instead. - HTTPSchemeKey = attribute.Key("http.scheme") - - // HTTPStatusCodeKey is the attribute Key conforming to the - // "http.status_code" semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 200 - // Deprecated: use `http.response.status_code` instead. - HTTPStatusCodeKey = attribute.Key("http.status_code") - - // HTTPTargetKey is the attribute Key conforming to the "http.target" - // semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '/search?q=OpenTelemetry#SemConv' - // Deprecated: use `url.path` and `url.query` instead. - HTTPTargetKey = attribute.Key("http.target") - - // HTTPURLKey is the attribute Key conforming to the "http.url" semantic - // conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv' - // Deprecated: use `url.full` instead. - HTTPURLKey = attribute.Key("http.url") - - // HTTPUserAgentKey is the attribute Key conforming to the - // "http.user_agent" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'CERN-LineMode/2.15 libwww/2.17b3', 'Mozilla/5.0 (iPhone; CPU - // iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) - // Version/14.1.2 Mobile/15E148 Safari/604.1' - // Deprecated: use `user_agent.original` instead. - HTTPUserAgentKey = attribute.Key("http.user_agent") -) - -var ( - // HTTP/1.0 - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorHTTP10 = HTTPFlavorKey.String("1.0") - // HTTP/1.1 - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorHTTP11 = HTTPFlavorKey.String("1.1") - // HTTP/2 - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorHTTP20 = HTTPFlavorKey.String("2.0") - // HTTP/3 - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorHTTP30 = HTTPFlavorKey.String("3.0") - // SPDY protocol - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorSPDY = HTTPFlavorKey.String("SPDY") - // QUIC protocol - // - // Deprecated: use `network.protocol.name` instead. - HTTPFlavorQUIC = HTTPFlavorKey.String("QUIC") -) - -// HTTPMethod returns an attribute KeyValue conforming to the "http.method" -// semantic conventions. -// -// Deprecated: use `http.request.method` instead. -func HTTPMethod(val string) attribute.KeyValue { - return HTTPMethodKey.String(val) -} - -// HTTPRequestContentLength returns an attribute KeyValue conforming to the -// "http.request_content_length" semantic conventions. -// -// Deprecated: use `http.request.header.content-length` instead. -func HTTPRequestContentLength(val int) attribute.KeyValue { - return HTTPRequestContentLengthKey.Int(val) -} - -// HTTPResponseContentLength returns an attribute KeyValue conforming to the -// "http.response_content_length" semantic conventions. -// -// Deprecated: use `http.response.header.content-length` instead. -func HTTPResponseContentLength(val int) attribute.KeyValue { - return HTTPResponseContentLengthKey.Int(val) -} - -// HTTPScheme returns an attribute KeyValue conforming to the "http.scheme" -// semantic conventions. -// -// Deprecated: use `url.scheme` instead. -func HTTPScheme(val string) attribute.KeyValue { - return HTTPSchemeKey.String(val) -} - -// HTTPStatusCode returns an attribute KeyValue conforming to the -// "http.status_code" semantic conventions. -// -// Deprecated: use `http.response.status_code` instead. -func HTTPStatusCode(val int) attribute.KeyValue { - return HTTPStatusCodeKey.Int(val) -} - -// HTTPTarget returns an attribute KeyValue conforming to the "http.target" -// semantic conventions. -// -// Deprecated: use `url.path` and `url.query` instead. -func HTTPTarget(val string) attribute.KeyValue { - return HTTPTargetKey.String(val) -} - -// HTTPURL returns an attribute KeyValue conforming to the "http.url" -// semantic conventions. -// -// Deprecated: use `url.full` instead. -func HTTPURL(val string) attribute.KeyValue { - return HTTPURLKey.String(val) -} - -// HTTPUserAgent returns an attribute KeyValue conforming to the -// "http.user_agent" semantic conventions. -// -// Deprecated: use `user_agent.original` instead. -func HTTPUserAgent(val string) attribute.KeyValue { - return HTTPUserAgentKey.String(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetHostNameKey is the attribute Key conforming to the "net.host.name" - // semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'example.com' - // Deprecated: use `server.address`. - NetHostNameKey = attribute.Key("net.host.name") - - // NetHostPortKey is the attribute Key conforming to the "net.host.port" - // semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 8080 - // Deprecated: use `server.port`. - NetHostPortKey = attribute.Key("net.host.port") - - // NetPeerNameKey is the attribute Key conforming to the "net.peer.name" - // semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'example.com' - // Deprecated: use `server.address` on client spans and `client.address` on - // server spans. - NetPeerNameKey = attribute.Key("net.peer.name") - - // NetPeerPortKey is the attribute Key conforming to the "net.peer.port" - // semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 8080 - // Deprecated: use `server.port` on client spans and `client.port` on - // server spans. - NetPeerPortKey = attribute.Key("net.peer.port") - - // NetProtocolNameKey is the attribute Key conforming to the - // "net.protocol.name" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'amqp', 'http', 'mqtt' - // Deprecated: use `network.protocol.name`. - NetProtocolNameKey = attribute.Key("net.protocol.name") - - // NetProtocolVersionKey is the attribute Key conforming to the - // "net.protocol.version" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '3.1.1' - // Deprecated: use `network.protocol.version`. - NetProtocolVersionKey = attribute.Key("net.protocol.version") - - // NetSockFamilyKey is the attribute Key conforming to the - // "net.sock.family" semantic conventions. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: deprecated - // Deprecated: use `network.transport` and `network.type`. - NetSockFamilyKey = attribute.Key("net.sock.family") - - // NetSockHostAddrKey is the attribute Key conforming to the - // "net.sock.host.addr" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '/var/my.sock' - // Deprecated: use `network.local.address`. - NetSockHostAddrKey = attribute.Key("net.sock.host.addr") - - // NetSockHostPortKey is the attribute Key conforming to the - // "net.sock.host.port" semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 8080 - // Deprecated: use `network.local.port`. - NetSockHostPortKey = attribute.Key("net.sock.host.port") - - // NetSockPeerAddrKey is the attribute Key conforming to the - // "net.sock.peer.addr" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '192.168.0.1' - // Deprecated: use `network.peer.address`. - NetSockPeerAddrKey = attribute.Key("net.sock.peer.addr") - - // NetSockPeerNameKey is the attribute Key conforming to the - // "net.sock.peer.name" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '/var/my.sock' - // Deprecated: no replacement at this time. - NetSockPeerNameKey = attribute.Key("net.sock.peer.name") - - // NetSockPeerPortKey is the attribute Key conforming to the - // "net.sock.peer.port" semantic conventions. - // - // Type: int - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 65531 - // Deprecated: use `network.peer.port`. - NetSockPeerPortKey = attribute.Key("net.sock.peer.port") - - // NetTransportKey is the attribute Key conforming to the "net.transport" - // semantic conventions. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: deprecated - // Deprecated: use `network.transport`. - NetTransportKey = attribute.Key("net.transport") -) - -var ( - // IPv4 address - // - // Deprecated: use `network.transport` and `network.type`. - NetSockFamilyInet = NetSockFamilyKey.String("inet") - // IPv6 address - // - // Deprecated: use `network.transport` and `network.type`. - NetSockFamilyInet6 = NetSockFamilyKey.String("inet6") - // Unix domain socket path - // - // Deprecated: use `network.transport` and `network.type`. - NetSockFamilyUnix = NetSockFamilyKey.String("unix") -) - -var ( - // ip_tcp - // - // Deprecated: use `network.transport`. - NetTransportTCP = NetTransportKey.String("ip_tcp") - // ip_udp - // - // Deprecated: use `network.transport`. - NetTransportUDP = NetTransportKey.String("ip_udp") - // Named or anonymous pipe - // - // Deprecated: use `network.transport`. - NetTransportPipe = NetTransportKey.String("pipe") - // In-process communication - // - // Deprecated: use `network.transport`. - NetTransportInProc = NetTransportKey.String("inproc") - // Something else (non IP-based) - // - // Deprecated: use `network.transport`. - NetTransportOther = NetTransportKey.String("other") -) - -// NetHostName returns an attribute KeyValue conforming to the -// "net.host.name" semantic conventions. -// -// Deprecated: use `server.address`. -func NetHostName(val string) attribute.KeyValue { - return NetHostNameKey.String(val) -} - -// NetHostPort returns an attribute KeyValue conforming to the -// "net.host.port" semantic conventions. -// -// Deprecated: use `server.port`. -func NetHostPort(val int) attribute.KeyValue { - return NetHostPortKey.Int(val) -} - -// NetPeerName returns an attribute KeyValue conforming to the -// "net.peer.name" semantic conventions. -// -// Deprecated: use `server.address` on client spans and `client.address` on -// server spans. -func NetPeerName(val string) attribute.KeyValue { - return NetPeerNameKey.String(val) -} - -// NetPeerPort returns an attribute KeyValue conforming to the -// "net.peer.port" semantic conventions. -// -// Deprecated: use `server.port` on client spans and `client.port` on server -// spans. -func NetPeerPort(val int) attribute.KeyValue { - return NetPeerPortKey.Int(val) -} - -// NetProtocolName returns an attribute KeyValue conforming to the -// "net.protocol.name" semantic conventions. -// -// Deprecated: use `network.protocol.name`. -func NetProtocolName(val string) attribute.KeyValue { - return NetProtocolNameKey.String(val) -} - -// NetProtocolVersion returns an attribute KeyValue conforming to the -// "net.protocol.version" semantic conventions. -// -// Deprecated: use `network.protocol.version`. -func NetProtocolVersion(val string) attribute.KeyValue { - return NetProtocolVersionKey.String(val) -} - -// NetSockHostAddr returns an attribute KeyValue conforming to the -// "net.sock.host.addr" semantic conventions. -// -// Deprecated: use `network.local.address`. -func NetSockHostAddr(val string) attribute.KeyValue { - return NetSockHostAddrKey.String(val) -} - -// NetSockHostPort returns an attribute KeyValue conforming to the -// "net.sock.host.port" semantic conventions. -// -// Deprecated: use `network.local.port`. -func NetSockHostPort(val int) attribute.KeyValue { - return NetSockHostPortKey.Int(val) -} - -// NetSockPeerAddr returns an attribute KeyValue conforming to the -// "net.sock.peer.addr" semantic conventions. -// -// Deprecated: use `network.peer.address`. -func NetSockPeerAddr(val string) attribute.KeyValue { - return NetSockPeerAddrKey.String(val) -} - -// NetSockPeerName returns an attribute KeyValue conforming to the -// "net.sock.peer.name" semantic conventions. -// -// Deprecated: no replacement at this time. -func NetSockPeerName(val string) attribute.KeyValue { - return NetSockPeerNameKey.String(val) -} - -// NetSockPeerPort returns an attribute KeyValue conforming to the -// "net.sock.peer.port" semantic conventions. -// -// Deprecated: use `network.peer.port`. -func NetSockPeerPort(val int) attribute.KeyValue { - return NetSockPeerPortKey.Int(val) -} - -// These attributes may be used to describe the receiver of a network -// exchange/packet. These should be used when there is no client/server -// relationship between the two sides, or when that relationship is unknown. -// This covers low-level network interactions (e.g. packet tracing) where you -// don't know if there was a connection or which side initiated it. This also -// covers unidirectional UDP flows and peer-to-peer communication where the -// "user-facing" surface of the protocol / API doesn't expose a clear notion of -// client and server. -const ( - // DestinationAddressKey is the attribute Key conforming to the - // "destination.address" semantic conventions. It represents the - // destination address - domain name if available without reverse DNS - // lookup; otherwise, IP address or Unix domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'destination.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the source side, and when communicating through - // an intermediary, `destination.address` SHOULD represent the destination - // address behind any intermediaries, for example proxies, if it's - // available. - DestinationAddressKey = attribute.Key("destination.address") - - // DestinationPortKey is the attribute Key conforming to the - // "destination.port" semantic conventions. It represents the destination - // port number - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3389, 2888 - DestinationPortKey = attribute.Key("destination.port") -) - -// DestinationAddress returns an attribute KeyValue conforming to the -// "destination.address" semantic conventions. It represents the destination -// address - domain name if available without reverse DNS lookup; otherwise, IP -// address or Unix domain socket name. -func DestinationAddress(val string) attribute.KeyValue { - return DestinationAddressKey.String(val) -} - -// DestinationPort returns an attribute KeyValue conforming to the -// "destination.port" semantic conventions. It represents the destination port -// number -func DestinationPort(val int) attribute.KeyValue { - return DestinationPortKey.Int(val) -} - -// These attributes may be used for any disk related operation. -const ( - // DiskIoDirectionKey is the attribute Key conforming to the - // "disk.io.direction" semantic conventions. It represents the disk IO - // operation direction. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'read' - DiskIoDirectionKey = attribute.Key("disk.io.direction") -) - -var ( - // read - DiskIoDirectionRead = DiskIoDirectionKey.String("read") - // write - DiskIoDirectionWrite = DiskIoDirectionKey.String("write") -) - -// The shared attributes used to report an error. -const ( - // ErrorTypeKey is the attribute Key conforming to the "error.type" - // semantic conventions. It represents the describes a class of error the - // operation ended with. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'timeout', 'java.net.UnknownHostException', - // 'server_certificate_invalid', '500' - // Note: The `error.type` SHOULD be predictable and SHOULD have low - // cardinality. - // Instrumentations SHOULD document the list of errors they report. - // - // The cardinality of `error.type` within one instrumentation library - // SHOULD be low. - // Telemetry consumers that aggregate data from multiple instrumentation - // libraries and applications - // should be prepared for `error.type` to have high cardinality at query - // time when no - // additional filters are applied. - // - // If the operation has completed successfully, instrumentations SHOULD NOT - // set `error.type`. - // - // If a specific domain defines its own set of error identifiers (such as - // HTTP or gRPC status codes), - // it's RECOMMENDED to: - // - // * Use a domain-specific attribute - // * Set `error.type` to capture all errors, regardless of whether they are - // defined within the domain-specific set or not. - ErrorTypeKey = attribute.Key("error.type") -) - -var ( - // A fallback error value to be used when the instrumentation doesn't define a custom value - ErrorTypeOther = ErrorTypeKey.String("_OTHER") -) - -// The shared attributes used to report a single exception associated with a -// span or log. -const ( - // ExceptionEscapedKey is the attribute Key conforming to the - // "exception.escaped" semantic conventions. It represents the sHOULD be - // set to true if the exception event is recorded at a point where it is - // known that the exception is escaping the scope of the span. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Note: An exception is considered to have escaped (or left) the scope of - // a span, - // if that span is ended while the exception is still logically "in - // flight". - // This may be actually "in flight" in some languages (e.g. if the - // exception - // is passed to a Context manager's `__exit__` method in Python) but will - // usually be caught at the point of recording the exception in most - // languages. - // - // It is usually not possible to determine at the point where an exception - // is thrown - // whether it will escape the scope of a span. - // However, it is trivial to know that an exception - // will escape, if one checks for an active exception just before ending - // the span, - // as done in the [example for recording span - // exceptions](#recording-an-exception). - // - // It follows that an exception may still escape the scope of the span - // even if the `exception.escaped` attribute was not set or set to false, - // since the event might have been recorded at a time where it was not - // clear whether the exception will escape. - ExceptionEscapedKey = attribute.Key("exception.escaped") - - // ExceptionMessageKey is the attribute Key conforming to the - // "exception.message" semantic conventions. It represents the exception - // message. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Division by zero', "Can't convert 'int' object to str - // implicitly" - ExceptionMessageKey = attribute.Key("exception.message") - - // ExceptionStacktraceKey is the attribute Key conforming to the - // "exception.stacktrace" semantic conventions. It represents a stacktrace - // as a string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Exception in thread "main" java.lang.RuntimeException: Test - // exception\\n at ' - // 'com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - ExceptionStacktraceKey = attribute.Key("exception.stacktrace") - - // ExceptionTypeKey is the attribute Key conforming to the "exception.type" - // semantic conventions. It represents the type of the exception (its - // fully-qualified class name, if applicable). The dynamic type of the - // exception should be preferred over the static type in languages that - // support it. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'java.net.ConnectException', 'OSError' - ExceptionTypeKey = attribute.Key("exception.type") -) - -// ExceptionEscaped returns an attribute KeyValue conforming to the -// "exception.escaped" semantic conventions. It represents the sHOULD be set to -// true if the exception event is recorded at a point where it is known that -// the exception is escaping the scope of the span. -func ExceptionEscaped(val bool) attribute.KeyValue { - return ExceptionEscapedKey.Bool(val) -} - -// ExceptionMessage returns an attribute KeyValue conforming to the -// "exception.message" semantic conventions. It represents the exception -// message. -func ExceptionMessage(val string) attribute.KeyValue { - return ExceptionMessageKey.String(val) -} - -// ExceptionStacktrace returns an attribute KeyValue conforming to the -// "exception.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func ExceptionStacktrace(val string) attribute.KeyValue { - return ExceptionStacktraceKey.String(val) -} - -// ExceptionType returns an attribute KeyValue conforming to the -// "exception.type" semantic conventions. It represents the type of the -// exception (its fully-qualified class name, if applicable). The dynamic type -// of the exception should be preferred over the static type in languages that -// support it. -func ExceptionType(val string) attribute.KeyValue { - return ExceptionTypeKey.String(val) -} - -// Semantic convention attributes in the HTTP namespace. -const ( - // HTTPRequestBodySizeKey is the attribute Key conforming to the - // "http.request.body.size" semantic conventions. It represents the size of - // the request payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3495 - HTTPRequestBodySizeKey = attribute.Key("http.request.body.size") - - // HTTPRequestMethodKey is the attribute Key conforming to the - // "http.request.method" semantic conventions. It represents the hTTP - // request method. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'GET', 'POST', 'HEAD' - // Note: HTTP request method value SHOULD be "known" to the - // instrumentation. - // By default, this convention defines "known" methods as the ones listed - // in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods) - // and the PATCH method defined in - // [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html). - // - // If the HTTP request method is not known to instrumentation, it MUST set - // the `http.request.method` attribute to `_OTHER`. - // - // If the HTTP instrumentation could end up converting valid HTTP request - // methods to `_OTHER`, then it MUST provide a way to override - // the list of known HTTP methods. If this override is done via environment - // variable, then the environment variable MUST be named - // OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated - // list of case-sensitive known HTTP methods - // (this list MUST be a full override of the default known method, it is - // not a list of known methods in addition to the defaults). - // - // HTTP method names are case-sensitive and `http.request.method` attribute - // value MUST match a known HTTP method name exactly. - // Instrumentations for specific web frameworks that consider HTTP methods - // to be case insensitive, SHOULD populate a canonical equivalent. - // Tracing instrumentations that do so, MUST also set - // `http.request.method_original` to the original value. - HTTPRequestMethodKey = attribute.Key("http.request.method") - - // HTTPRequestMethodOriginalKey is the attribute Key conforming to the - // "http.request.method_original" semantic conventions. It represents the - // original HTTP method sent by the client in the request line. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'GeT', 'ACL', 'foo' - HTTPRequestMethodOriginalKey = attribute.Key("http.request.method_original") - - // HTTPRequestResendCountKey is the attribute Key conforming to the - // "http.request.resend_count" semantic conventions. It represents the - // ordinal number of request resending attempt (for any reason, including - // redirects). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 3 - // Note: The resend count SHOULD be updated each time an HTTP request gets - // resent by the client, regardless of what was the cause of the resending - // (e.g. redirection, authorization failure, 503 Server Unavailable, - // network issues, or any other). - HTTPRequestResendCountKey = attribute.Key("http.request.resend_count") - - // HTTPResponseBodySizeKey is the attribute Key conforming to the - // "http.response.body.size" semantic conventions. It represents the size - // of the response payload body in bytes. This is the number of bytes - // transferred excluding headers and is often, but not always, present as - // the - // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) - // header. For requests using transport encoding, this should be the - // compressed size. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3495 - HTTPResponseBodySizeKey = attribute.Key("http.response.body.size") - - // HTTPResponseStatusCodeKey is the attribute Key conforming to the - // "http.response.status_code" semantic conventions. It represents the - // [HTTP response status - // code](https://tools.ietf.org/html/rfc7231#section-6). - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 200 - HTTPResponseStatusCodeKey = attribute.Key("http.response.status_code") - - // HTTPRouteKey is the attribute Key conforming to the "http.route" - // semantic conventions. It represents the matched route, that is, the path - // template in the format used by the respective server framework. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/users/:userID?', '{controller}/{action}/{id?}' - // Note: MUST NOT be populated when this is not supported by the HTTP - // server framework as the route attribute should have low-cardinality and - // the URI path can NOT substitute it. - // SHOULD include the [application - // root](/docs/http/http-spans.md#http-server-definitions) if there is one. - HTTPRouteKey = attribute.Key("http.route") -) - -var ( - // CONNECT method - HTTPRequestMethodConnect = HTTPRequestMethodKey.String("CONNECT") - // DELETE method - HTTPRequestMethodDelete = HTTPRequestMethodKey.String("DELETE") - // GET method - HTTPRequestMethodGet = HTTPRequestMethodKey.String("GET") - // HEAD method - HTTPRequestMethodHead = HTTPRequestMethodKey.String("HEAD") - // OPTIONS method - HTTPRequestMethodOptions = HTTPRequestMethodKey.String("OPTIONS") - // PATCH method - HTTPRequestMethodPatch = HTTPRequestMethodKey.String("PATCH") - // POST method - HTTPRequestMethodPost = HTTPRequestMethodKey.String("POST") - // PUT method - HTTPRequestMethodPut = HTTPRequestMethodKey.String("PUT") - // TRACE method - HTTPRequestMethodTrace = HTTPRequestMethodKey.String("TRACE") - // Any HTTP method that the instrumentation has no prior knowledge of - HTTPRequestMethodOther = HTTPRequestMethodKey.String("_OTHER") -) - -// HTTPRequestBodySize returns an attribute KeyValue conforming to the -// "http.request.body.size" semantic conventions. It represents the size of the -// request payload body in bytes. This is the number of bytes transferred -// excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPRequestBodySize(val int) attribute.KeyValue { - return HTTPRequestBodySizeKey.Int(val) -} - -// HTTPRequestMethodOriginal returns an attribute KeyValue conforming to the -// "http.request.method_original" semantic conventions. It represents the -// original HTTP method sent by the client in the request line. -func HTTPRequestMethodOriginal(val string) attribute.KeyValue { - return HTTPRequestMethodOriginalKey.String(val) -} - -// HTTPRequestResendCount returns an attribute KeyValue conforming to the -// "http.request.resend_count" semantic conventions. It represents the ordinal -// number of request resending attempt (for any reason, including redirects). -func HTTPRequestResendCount(val int) attribute.KeyValue { - return HTTPRequestResendCountKey.Int(val) -} - -// HTTPResponseBodySize returns an attribute KeyValue conforming to the -// "http.response.body.size" semantic conventions. It represents the size of -// the response payload body in bytes. This is the number of bytes transferred -// excluding headers and is often, but not always, present as the -// [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) -// header. For requests using transport encoding, this should be the compressed -// size. -func HTTPResponseBodySize(val int) attribute.KeyValue { - return HTTPResponseBodySizeKey.Int(val) -} - -// HTTPResponseStatusCode returns an attribute KeyValue conforming to the -// "http.response.status_code" semantic conventions. It represents the [HTTP -// response status code](https://tools.ietf.org/html/rfc7231#section-6). -func HTTPResponseStatusCode(val int) attribute.KeyValue { - return HTTPResponseStatusCodeKey.Int(val) -} - -// HTTPRoute returns an attribute KeyValue conforming to the "http.route" -// semantic conventions. It represents the matched route, that is, the path -// template in the format used by the respective server framework. -func HTTPRoute(val string) attribute.KeyValue { - return HTTPRouteKey.String(val) -} - -// Attributes describing telemetry around messaging systems and messaging -// activities. -const ( - // MessagingBatchMessageCountKey is the attribute Key conforming to the - // "messaging.batch.message_count" semantic conventions. It represents the - // number of messages sent, received, or processed in the scope of the - // batching operation. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 1, 2 - // Note: Instrumentations SHOULD NOT set `messaging.batch.message_count` on - // spans that operate with a single message. When a messaging client - // library supports both batch and single-message API for the same - // operation, instrumentations SHOULD use `messaging.batch.message_count` - // for batching APIs and SHOULD NOT use it for single-message APIs. - MessagingBatchMessageCountKey = attribute.Key("messaging.batch.message_count") - - // MessagingClientIDKey is the attribute Key conforming to the - // "messaging.client_id" semantic conventions. It represents a unique - // identifier for the client that consumes or produces a message. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'client-5', 'myhost@8742@s8083jm' - MessagingClientIDKey = attribute.Key("messaging.client_id") - - // MessagingDestinationAnonymousKey is the attribute Key conforming to the - // "messaging.destination.anonymous" semantic conventions. It represents a - // boolean that is true if the message destination is anonymous (could be - // unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationAnonymousKey = attribute.Key("messaging.destination.anonymous") - - // MessagingDestinationNameKey is the attribute Key conforming to the - // "messaging.destination.name" semantic conventions. It represents the - // message destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyQueue', 'MyTopic' - // Note: Destination name SHOULD uniquely identify a specific queue, topic - // or other entity within the broker. If - // the broker doesn't have such notion, the destination name SHOULD - // uniquely identify the broker. - MessagingDestinationNameKey = attribute.Key("messaging.destination.name") - - // MessagingDestinationTemplateKey is the attribute Key conforming to the - // "messaging.destination.template" semantic conventions. It represents the - // low cardinality representation of the messaging destination name - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/customers/{customerID}' - // Note: Destination names could be constructed from templates. An example - // would be a destination name involving a user name or product id. - // Although the destination name in this case is of high cardinality, the - // underlying template is of low cardinality and can be effectively used - // for grouping and aggregation. - MessagingDestinationTemplateKey = attribute.Key("messaging.destination.template") - - // MessagingDestinationTemporaryKey is the attribute Key conforming to the - // "messaging.destination.temporary" semantic conventions. It represents a - // boolean that is true if the message destination is temporary and might - // not exist anymore after messages are processed. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationTemporaryKey = attribute.Key("messaging.destination.temporary") - - // MessagingDestinationPublishAnonymousKey is the attribute Key conforming - // to the "messaging.destination_publish.anonymous" semantic conventions. - // It represents a boolean that is true if the publish message destination - // is anonymous (could be unnamed or have auto-generated name). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingDestinationPublishAnonymousKey = attribute.Key("messaging.destination_publish.anonymous") - - // MessagingDestinationPublishNameKey is the attribute Key conforming to - // the "messaging.destination_publish.name" semantic conventions. It - // represents the name of the original destination the message was - // published to - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyQueue', 'MyTopic' - // Note: The name SHOULD uniquely identify a specific queue, topic, or - // other entity within the broker. If - // the broker doesn't have such notion, the original destination name - // SHOULD uniquely identify the broker. - MessagingDestinationPublishNameKey = attribute.Key("messaging.destination_publish.name") - - // MessagingGCPPubsubMessageOrderingKeyKey is the attribute Key conforming - // to the "messaging.gcp_pubsub.message.ordering_key" semantic conventions. - // It represents the ordering key for a given message. If the attribute is - // not present, the message does not have an ordering key. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ordering_key' - MessagingGCPPubsubMessageOrderingKeyKey = attribute.Key("messaging.gcp_pubsub.message.ordering_key") - - // MessagingKafkaConsumerGroupKey is the attribute Key conforming to the - // "messaging.kafka.consumer.group" semantic conventions. It represents the - // name of the Kafka Consumer Group that is handling the message. Only - // applies to consumers, not producers. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-group' - MessagingKafkaConsumerGroupKey = attribute.Key("messaging.kafka.consumer.group") - - // MessagingKafkaDestinationPartitionKey is the attribute Key conforming to - // the "messaging.kafka.destination.partition" semantic conventions. It - // represents the partition the message is sent to. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 2 - MessagingKafkaDestinationPartitionKey = attribute.Key("messaging.kafka.destination.partition") - - // MessagingKafkaMessageKeyKey is the attribute Key conforming to the - // "messaging.kafka.message.key" semantic conventions. It represents the - // message keys in Kafka are used for grouping alike messages to ensure - // they're processed on the same partition. They differ from - // `messaging.message.id` in that they're not unique. If the key is `null`, - // the attribute MUST NOT be set. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myKey' - // Note: If the key type is not string, it's string representation has to - // be supplied for the attribute. If the key has no unambiguous, canonical - // string form, don't include its value. - MessagingKafkaMessageKeyKey = attribute.Key("messaging.kafka.message.key") - - // MessagingKafkaMessageOffsetKey is the attribute Key conforming to the - // "messaging.kafka.message.offset" semantic conventions. It represents the - // offset of a record in the corresponding Kafka partition. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - MessagingKafkaMessageOffsetKey = attribute.Key("messaging.kafka.message.offset") - - // MessagingKafkaMessageTombstoneKey is the attribute Key conforming to the - // "messaging.kafka.message.tombstone" semantic conventions. It represents - // a boolean that is true if the message is a tombstone. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - MessagingKafkaMessageTombstoneKey = attribute.Key("messaging.kafka.message.tombstone") - - // MessagingMessageBodySizeKey is the attribute Key conforming to the - // "messaging.message.body.size" semantic conventions. It represents the - // size of the message body in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1439 - // Note: This can refer to both the compressed or uncompressed body size. - // If both sizes are known, the uncompressed - // body size should be used. - MessagingMessageBodySizeKey = attribute.Key("messaging.message.body.size") - - // MessagingMessageConversationIDKey is the attribute Key conforming to the - // "messaging.message.conversation_id" semantic conventions. It represents - // the conversation ID identifying the conversation to which the message - // belongs, represented as a string. Sometimes called "Correlation ID". - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MyConversationID' - MessagingMessageConversationIDKey = attribute.Key("messaging.message.conversation_id") - - // MessagingMessageEnvelopeSizeKey is the attribute Key conforming to the - // "messaging.message.envelope.size" semantic conventions. It represents - // the size of the message body and metadata in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 2738 - // Note: This can refer to both the compressed or uncompressed size. If - // both sizes are known, the uncompressed - // size should be used. - MessagingMessageEnvelopeSizeKey = attribute.Key("messaging.message.envelope.size") - - // MessagingMessageIDKey is the attribute Key conforming to the - // "messaging.message.id" semantic conventions. It represents a value used - // by the messaging system as an identifier for the message, represented as - // a string. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '452a7c7c7c7048c2f887f61572b18fc2' - MessagingMessageIDKey = attribute.Key("messaging.message.id") - - // MessagingOperationKey is the attribute Key conforming to the - // "messaging.operation" semantic conventions. It represents a string - // identifying the kind of messaging operation. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: If a custom value is used, it MUST be of low cardinality. - MessagingOperationKey = attribute.Key("messaging.operation") - - // MessagingRabbitmqDestinationRoutingKeyKey is the attribute Key - // conforming to the "messaging.rabbitmq.destination.routing_key" semantic - // conventions. It represents the rabbitMQ message routing key. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myKey' - MessagingRabbitmqDestinationRoutingKeyKey = attribute.Key("messaging.rabbitmq.destination.routing_key") - - // MessagingRocketmqClientGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.client_group" semantic conventions. It represents - // the name of the RocketMQ producer/consumer group that is handling the - // message. The client type is identified by the SpanKind. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myConsumerGroup' - MessagingRocketmqClientGroupKey = attribute.Key("messaging.rocketmq.client_group") - - // MessagingRocketmqConsumptionModelKey is the attribute Key conforming to - // the "messaging.rocketmq.consumption_model" semantic conventions. It - // represents the model of message consumption. This only applies to - // consumer spans. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingRocketmqConsumptionModelKey = attribute.Key("messaging.rocketmq.consumption_model") - - // MessagingRocketmqMessageDelayTimeLevelKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delay_time_level" semantic - // conventions. It represents the delay time level for delay message, which - // determines the message delay time. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3 - MessagingRocketmqMessageDelayTimeLevelKey = attribute.Key("messaging.rocketmq.message.delay_time_level") - - // MessagingRocketmqMessageDeliveryTimestampKey is the attribute Key - // conforming to the "messaging.rocketmq.message.delivery_timestamp" - // semantic conventions. It represents the timestamp in milliseconds that - // the delay message is expected to be delivered to consumer. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1665987217045 - MessagingRocketmqMessageDeliveryTimestampKey = attribute.Key("messaging.rocketmq.message.delivery_timestamp") - - // MessagingRocketmqMessageGroupKey is the attribute Key conforming to the - // "messaging.rocketmq.message.group" semantic conventions. It represents - // the it is essential for FIFO message. Messages that belong to the same - // message group are always processed one by one within the same consumer - // group. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myMessageGroup' - MessagingRocketmqMessageGroupKey = attribute.Key("messaging.rocketmq.message.group") - - // MessagingRocketmqMessageKeysKey is the attribute Key conforming to the - // "messaging.rocketmq.message.keys" semantic conventions. It represents - // the key(s) of message, another way to mark message besides message id. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'keyA', 'keyB' - MessagingRocketmqMessageKeysKey = attribute.Key("messaging.rocketmq.message.keys") - - // MessagingRocketmqMessageTagKey is the attribute Key conforming to the - // "messaging.rocketmq.message.tag" semantic conventions. It represents the - // secondary classifier of message besides topic. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'tagA' - MessagingRocketmqMessageTagKey = attribute.Key("messaging.rocketmq.message.tag") - - // MessagingRocketmqMessageTypeKey is the attribute Key conforming to the - // "messaging.rocketmq.message.type" semantic conventions. It represents - // the type of message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingRocketmqMessageTypeKey = attribute.Key("messaging.rocketmq.message.type") - - // MessagingRocketmqNamespaceKey is the attribute Key conforming to the - // "messaging.rocketmq.namespace" semantic conventions. It represents the - // namespace of RocketMQ resources, resources in different namespaces are - // individual. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myNamespace' - MessagingRocketmqNamespaceKey = attribute.Key("messaging.rocketmq.namespace") - - // MessagingSystemKey is the attribute Key conforming to the - // "messaging.system" semantic conventions. It represents an identifier for - // the messaging system being used. See below for a list of well-known - // identifiers. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessagingSystemKey = attribute.Key("messaging.system") -) - -var ( - // One or more messages are provided for publishing to an intermediary. If a single message is published, the context of the "Publish" span can be used as the creation context and no "Create" span needs to be created - MessagingOperationPublish = MessagingOperationKey.String("publish") - // A message is created. "Create" spans always refer to a single message and are used to provide a unique creation context for messages in batch publishing scenarios - MessagingOperationCreate = MessagingOperationKey.String("create") - // One or more messages are requested by a consumer. This operation refers to pull-based scenarios, where consumers explicitly call methods of messaging SDKs to receive messages - MessagingOperationReceive = MessagingOperationKey.String("receive") - // One or more messages are passed to a consumer. This operation refers to push-based scenarios, where consumer register callbacks which get called by messaging SDKs - MessagingOperationDeliver = MessagingOperationKey.String("deliver") -) - -var ( - // Clustering consumption model - MessagingRocketmqConsumptionModelClustering = MessagingRocketmqConsumptionModelKey.String("clustering") - // Broadcasting consumption model - MessagingRocketmqConsumptionModelBroadcasting = MessagingRocketmqConsumptionModelKey.String("broadcasting") -) - -var ( - // Normal message - MessagingRocketmqMessageTypeNormal = MessagingRocketmqMessageTypeKey.String("normal") - // FIFO message - MessagingRocketmqMessageTypeFifo = MessagingRocketmqMessageTypeKey.String("fifo") - // Delay message - MessagingRocketmqMessageTypeDelay = MessagingRocketmqMessageTypeKey.String("delay") - // Transaction message - MessagingRocketmqMessageTypeTransaction = MessagingRocketmqMessageTypeKey.String("transaction") -) - -var ( - // Apache ActiveMQ - MessagingSystemActivemq = MessagingSystemKey.String("activemq") - // Amazon Simple Queue Service (SQS) - MessagingSystemAWSSqs = MessagingSystemKey.String("aws_sqs") - // Azure Event Grid - MessagingSystemAzureEventgrid = MessagingSystemKey.String("azure_eventgrid") - // Azure Event Hubs - MessagingSystemAzureEventhubs = MessagingSystemKey.String("azure_eventhubs") - // Azure Service Bus - MessagingSystemAzureServicebus = MessagingSystemKey.String("azure_servicebus") - // Google Cloud Pub/Sub - MessagingSystemGCPPubsub = MessagingSystemKey.String("gcp_pubsub") - // Java Message Service - MessagingSystemJms = MessagingSystemKey.String("jms") - // Apache Kafka - MessagingSystemKafka = MessagingSystemKey.String("kafka") - // RabbitMQ - MessagingSystemRabbitmq = MessagingSystemKey.String("rabbitmq") - // Apache RocketMQ - MessagingSystemRocketmq = MessagingSystemKey.String("rocketmq") -) - -// MessagingBatchMessageCount returns an attribute KeyValue conforming to -// the "messaging.batch.message_count" semantic conventions. It represents the -// number of messages sent, received, or processed in the scope of the batching -// operation. -func MessagingBatchMessageCount(val int) attribute.KeyValue { - return MessagingBatchMessageCountKey.Int(val) -} - -// MessagingClientID returns an attribute KeyValue conforming to the -// "messaging.client_id" semantic conventions. It represents a unique -// identifier for the client that consumes or produces a message. -func MessagingClientID(val string) attribute.KeyValue { - return MessagingClientIDKey.String(val) -} - -// MessagingDestinationAnonymous returns an attribute KeyValue conforming to -// the "messaging.destination.anonymous" semantic conventions. It represents a -// boolean that is true if the message destination is anonymous (could be -// unnamed or have auto-generated name). -func MessagingDestinationAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationAnonymousKey.Bool(val) -} - -// MessagingDestinationName returns an attribute KeyValue conforming to the -// "messaging.destination.name" semantic conventions. It represents the message -// destination name -func MessagingDestinationName(val string) attribute.KeyValue { - return MessagingDestinationNameKey.String(val) -} - -// MessagingDestinationTemplate returns an attribute KeyValue conforming to -// the "messaging.destination.template" semantic conventions. It represents the -// low cardinality representation of the messaging destination name -func MessagingDestinationTemplate(val string) attribute.KeyValue { - return MessagingDestinationTemplateKey.String(val) -} - -// MessagingDestinationTemporary returns an attribute KeyValue conforming to -// the "messaging.destination.temporary" semantic conventions. It represents a -// boolean that is true if the message destination is temporary and might not -// exist anymore after messages are processed. -func MessagingDestinationTemporary(val bool) attribute.KeyValue { - return MessagingDestinationTemporaryKey.Bool(val) -} - -// MessagingDestinationPublishAnonymous returns an attribute KeyValue -// conforming to the "messaging.destination_publish.anonymous" semantic -// conventions. It represents a boolean that is true if the publish message -// destination is anonymous (could be unnamed or have auto-generated name). -func MessagingDestinationPublishAnonymous(val bool) attribute.KeyValue { - return MessagingDestinationPublishAnonymousKey.Bool(val) -} - -// MessagingDestinationPublishName returns an attribute KeyValue conforming -// to the "messaging.destination_publish.name" semantic conventions. It -// represents the name of the original destination the message was published to -func MessagingDestinationPublishName(val string) attribute.KeyValue { - return MessagingDestinationPublishNameKey.String(val) -} - -// MessagingGCPPubsubMessageOrderingKey returns an attribute KeyValue -// conforming to the "messaging.gcp_pubsub.message.ordering_key" semantic -// conventions. It represents the ordering key for a given message. If the -// attribute is not present, the message does not have an ordering key. -func MessagingGCPPubsubMessageOrderingKey(val string) attribute.KeyValue { - return MessagingGCPPubsubMessageOrderingKeyKey.String(val) -} - -// MessagingKafkaConsumerGroup returns an attribute KeyValue conforming to -// the "messaging.kafka.consumer.group" semantic conventions. It represents the -// name of the Kafka Consumer Group that is handling the message. Only applies -// to consumers, not producers. -func MessagingKafkaConsumerGroup(val string) attribute.KeyValue { - return MessagingKafkaConsumerGroupKey.String(val) -} - -// MessagingKafkaDestinationPartition returns an attribute KeyValue -// conforming to the "messaging.kafka.destination.partition" semantic -// conventions. It represents the partition the message is sent to. -func MessagingKafkaDestinationPartition(val int) attribute.KeyValue { - return MessagingKafkaDestinationPartitionKey.Int(val) -} - -// MessagingKafkaMessageKey returns an attribute KeyValue conforming to the -// "messaging.kafka.message.key" semantic conventions. It represents the -// message keys in Kafka are used for grouping alike messages to ensure they're -// processed on the same partition. They differ from `messaging.message.id` in -// that they're not unique. If the key is `null`, the attribute MUST NOT be -// set. -func MessagingKafkaMessageKey(val string) attribute.KeyValue { - return MessagingKafkaMessageKeyKey.String(val) -} - -// MessagingKafkaMessageOffset returns an attribute KeyValue conforming to -// the "messaging.kafka.message.offset" semantic conventions. It represents the -// offset of a record in the corresponding Kafka partition. -func MessagingKafkaMessageOffset(val int) attribute.KeyValue { - return MessagingKafkaMessageOffsetKey.Int(val) -} - -// MessagingKafkaMessageTombstone returns an attribute KeyValue conforming -// to the "messaging.kafka.message.tombstone" semantic conventions. It -// represents a boolean that is true if the message is a tombstone. -func MessagingKafkaMessageTombstone(val bool) attribute.KeyValue { - return MessagingKafkaMessageTombstoneKey.Bool(val) -} - -// MessagingMessageBodySize returns an attribute KeyValue conforming to the -// "messaging.message.body.size" semantic conventions. It represents the size -// of the message body in bytes. -func MessagingMessageBodySize(val int) attribute.KeyValue { - return MessagingMessageBodySizeKey.Int(val) -} - -// MessagingMessageConversationID returns an attribute KeyValue conforming -// to the "messaging.message.conversation_id" semantic conventions. It -// represents the conversation ID identifying the conversation to which the -// message belongs, represented as a string. Sometimes called "Correlation ID". -func MessagingMessageConversationID(val string) attribute.KeyValue { - return MessagingMessageConversationIDKey.String(val) -} - -// MessagingMessageEnvelopeSize returns an attribute KeyValue conforming to -// the "messaging.message.envelope.size" semantic conventions. It represents -// the size of the message body and metadata in bytes. -func MessagingMessageEnvelopeSize(val int) attribute.KeyValue { - return MessagingMessageEnvelopeSizeKey.Int(val) -} - -// MessagingMessageID returns an attribute KeyValue conforming to the -// "messaging.message.id" semantic conventions. It represents a value used by -// the messaging system as an identifier for the message, represented as a -// string. -func MessagingMessageID(val string) attribute.KeyValue { - return MessagingMessageIDKey.String(val) -} - -// MessagingRabbitmqDestinationRoutingKey returns an attribute KeyValue -// conforming to the "messaging.rabbitmq.destination.routing_key" semantic -// conventions. It represents the rabbitMQ message routing key. -func MessagingRabbitmqDestinationRoutingKey(val string) attribute.KeyValue { - return MessagingRabbitmqDestinationRoutingKeyKey.String(val) -} - -// MessagingRocketmqClientGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.client_group" semantic conventions. It represents -// the name of the RocketMQ producer/consumer group that is handling the -// message. The client type is identified by the SpanKind. -func MessagingRocketmqClientGroup(val string) attribute.KeyValue { - return MessagingRocketmqClientGroupKey.String(val) -} - -// MessagingRocketmqMessageDelayTimeLevel returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delay_time_level" semantic -// conventions. It represents the delay time level for delay message, which -// determines the message delay time. -func MessagingRocketmqMessageDelayTimeLevel(val int) attribute.KeyValue { - return MessagingRocketmqMessageDelayTimeLevelKey.Int(val) -} - -// MessagingRocketmqMessageDeliveryTimestamp returns an attribute KeyValue -// conforming to the "messaging.rocketmq.message.delivery_timestamp" semantic -// conventions. It represents the timestamp in milliseconds that the delay -// message is expected to be delivered to consumer. -func MessagingRocketmqMessageDeliveryTimestamp(val int) attribute.KeyValue { - return MessagingRocketmqMessageDeliveryTimestampKey.Int(val) -} - -// MessagingRocketmqMessageGroup returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.group" semantic conventions. It represents -// the it is essential for FIFO message. Messages that belong to the same -// message group are always processed one by one within the same consumer -// group. -func MessagingRocketmqMessageGroup(val string) attribute.KeyValue { - return MessagingRocketmqMessageGroupKey.String(val) -} - -// MessagingRocketmqMessageKeys returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.keys" semantic conventions. It represents -// the key(s) of message, another way to mark message besides message id. -func MessagingRocketmqMessageKeys(val ...string) attribute.KeyValue { - return MessagingRocketmqMessageKeysKey.StringSlice(val) -} - -// MessagingRocketmqMessageTag returns an attribute KeyValue conforming to -// the "messaging.rocketmq.message.tag" semantic conventions. It represents the -// secondary classifier of message besides topic. -func MessagingRocketmqMessageTag(val string) attribute.KeyValue { - return MessagingRocketmqMessageTagKey.String(val) -} - -// MessagingRocketmqNamespace returns an attribute KeyValue conforming to -// the "messaging.rocketmq.namespace" semantic conventions. It represents the -// namespace of RocketMQ resources, resources in different namespaces are -// individual. -func MessagingRocketmqNamespace(val string) attribute.KeyValue { - return MessagingRocketmqNamespaceKey.String(val) -} - -// These attributes may be used for any network related operation. -const ( - // NetworkCarrierIccKey is the attribute Key conforming to the - // "network.carrier.icc" semantic conventions. It represents the ISO 3166-1 - // alpha-2 2-character country code associated with the mobile carrier - // network. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'DE' - NetworkCarrierIccKey = attribute.Key("network.carrier.icc") - - // NetworkCarrierMccKey is the attribute Key conforming to the - // "network.carrier.mcc" semantic conventions. It represents the mobile - // carrier country code. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '310' - NetworkCarrierMccKey = attribute.Key("network.carrier.mcc") - - // NetworkCarrierMncKey is the attribute Key conforming to the - // "network.carrier.mnc" semantic conventions. It represents the mobile - // carrier network code. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '001' - NetworkCarrierMncKey = attribute.Key("network.carrier.mnc") - - // NetworkCarrierNameKey is the attribute Key conforming to the - // "network.carrier.name" semantic conventions. It represents the name of - // the mobile carrier. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'sprint' - NetworkCarrierNameKey = attribute.Key("network.carrier.name") - - // NetworkConnectionSubtypeKey is the attribute Key conforming to the - // "network.connection.subtype" semantic conventions. It represents the - // this describes more details regarding the connection.type. It may be the - // type of cell technology connection, but it could be used for describing - // details about a wifi connection. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'LTE' - NetworkConnectionSubtypeKey = attribute.Key("network.connection.subtype") - - // NetworkConnectionTypeKey is the attribute Key conforming to the - // "network.connection.type" semantic conventions. It represents the - // internet connection type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'wifi' - NetworkConnectionTypeKey = attribute.Key("network.connection.type") - - // NetworkIoDirectionKey is the attribute Key conforming to the - // "network.io.direction" semantic conventions. It represents the network - // IO operation direction. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'transmit' - NetworkIoDirectionKey = attribute.Key("network.io.direction") - - // NetworkLocalAddressKey is the attribute Key conforming to the - // "network.local.address" semantic conventions. It represents the local - // address of the network connection - IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10.1.2.80', '/tmp/my.sock' - NetworkLocalAddressKey = attribute.Key("network.local.address") - - // NetworkLocalPortKey is the attribute Key conforming to the - // "network.local.port" semantic conventions. It represents the local port - // number of the network connection. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - NetworkLocalPortKey = attribute.Key("network.local.port") - - // NetworkPeerAddressKey is the attribute Key conforming to the - // "network.peer.address" semantic conventions. It represents the peer - // address of the network connection - IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '10.1.2.80', '/tmp/my.sock' - NetworkPeerAddressKey = attribute.Key("network.peer.address") - - // NetworkPeerPortKey is the attribute Key conforming to the - // "network.peer.port" semantic conventions. It represents the peer port - // number of the network connection. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 65123 - NetworkPeerPortKey = attribute.Key("network.peer.port") - - // NetworkProtocolNameKey is the attribute Key conforming to the - // "network.protocol.name" semantic conventions. It represents the [OSI - // application layer](https://osi-model.com/application-layer/) or non-OSI - // equivalent. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'amqp', 'http', 'mqtt' - // Note: The value SHOULD be normalized to lowercase. - NetworkProtocolNameKey = attribute.Key("network.protocol.name") - - // NetworkProtocolVersionKey is the attribute Key conforming to the - // "network.protocol.version" semantic conventions. It represents the - // version of the protocol specified in `network.protocol.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '3.1.1' - // Note: `network.protocol.version` refers to the version of the protocol - // used and might be different from the protocol client's version. If the - // HTTP client has a version of `0.27.2`, but sends HTTP version `1.1`, - // this attribute should be set to `1.1`. - NetworkProtocolVersionKey = attribute.Key("network.protocol.version") - - // NetworkTransportKey is the attribute Key conforming to the - // "network.transport" semantic conventions. It represents the [OSI - // transport layer](https://osi-model.com/transport-layer/) or - // [inter-process communication - // method](https://wikipedia.org/wiki/Inter-process_communication). - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'tcp', 'udp' - // Note: The value SHOULD be normalized to lowercase. - // - // Consider always setting the transport when setting a port number, since - // a port number is ambiguous without knowing the transport. For example - // different processes could be listening on TCP port 12345 and UDP port - // 12345. - NetworkTransportKey = attribute.Key("network.transport") - - // NetworkTypeKey is the attribute Key conforming to the "network.type" - // semantic conventions. It represents the [OSI network - // layer](https://osi-model.com/network-layer/) or non-OSI equivalent. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: stable - // Examples: 'ipv4', 'ipv6' - // Note: The value SHOULD be normalized to lowercase. - NetworkTypeKey = attribute.Key("network.type") -) - -var ( - // GPRS - NetworkConnectionSubtypeGprs = NetworkConnectionSubtypeKey.String("gprs") - // EDGE - NetworkConnectionSubtypeEdge = NetworkConnectionSubtypeKey.String("edge") - // UMTS - NetworkConnectionSubtypeUmts = NetworkConnectionSubtypeKey.String("umts") - // CDMA - NetworkConnectionSubtypeCdma = NetworkConnectionSubtypeKey.String("cdma") - // EVDO Rel. 0 - NetworkConnectionSubtypeEvdo0 = NetworkConnectionSubtypeKey.String("evdo_0") - // EVDO Rev. A - NetworkConnectionSubtypeEvdoA = NetworkConnectionSubtypeKey.String("evdo_a") - // CDMA2000 1XRTT - NetworkConnectionSubtypeCdma20001xrtt = NetworkConnectionSubtypeKey.String("cdma2000_1xrtt") - // HSDPA - NetworkConnectionSubtypeHsdpa = NetworkConnectionSubtypeKey.String("hsdpa") - // HSUPA - NetworkConnectionSubtypeHsupa = NetworkConnectionSubtypeKey.String("hsupa") - // HSPA - NetworkConnectionSubtypeHspa = NetworkConnectionSubtypeKey.String("hspa") - // IDEN - NetworkConnectionSubtypeIden = NetworkConnectionSubtypeKey.String("iden") - // EVDO Rev. B - NetworkConnectionSubtypeEvdoB = NetworkConnectionSubtypeKey.String("evdo_b") - // LTE - NetworkConnectionSubtypeLte = NetworkConnectionSubtypeKey.String("lte") - // EHRPD - NetworkConnectionSubtypeEhrpd = NetworkConnectionSubtypeKey.String("ehrpd") - // HSPAP - NetworkConnectionSubtypeHspap = NetworkConnectionSubtypeKey.String("hspap") - // GSM - NetworkConnectionSubtypeGsm = NetworkConnectionSubtypeKey.String("gsm") - // TD-SCDMA - NetworkConnectionSubtypeTdScdma = NetworkConnectionSubtypeKey.String("td_scdma") - // IWLAN - NetworkConnectionSubtypeIwlan = NetworkConnectionSubtypeKey.String("iwlan") - // 5G NR (New Radio) - NetworkConnectionSubtypeNr = NetworkConnectionSubtypeKey.String("nr") - // 5G NRNSA (New Radio Non-Standalone) - NetworkConnectionSubtypeNrnsa = NetworkConnectionSubtypeKey.String("nrnsa") - // LTE CA - NetworkConnectionSubtypeLteCa = NetworkConnectionSubtypeKey.String("lte_ca") -) - -var ( - // wifi - NetworkConnectionTypeWifi = NetworkConnectionTypeKey.String("wifi") - // wired - NetworkConnectionTypeWired = NetworkConnectionTypeKey.String("wired") - // cell - NetworkConnectionTypeCell = NetworkConnectionTypeKey.String("cell") - // unavailable - NetworkConnectionTypeUnavailable = NetworkConnectionTypeKey.String("unavailable") - // unknown - NetworkConnectionTypeUnknown = NetworkConnectionTypeKey.String("unknown") -) - -var ( - // transmit - NetworkIoDirectionTransmit = NetworkIoDirectionKey.String("transmit") - // receive - NetworkIoDirectionReceive = NetworkIoDirectionKey.String("receive") -) - -var ( - // TCP - NetworkTransportTCP = NetworkTransportKey.String("tcp") - // UDP - NetworkTransportUDP = NetworkTransportKey.String("udp") - // Named or anonymous pipe - NetworkTransportPipe = NetworkTransportKey.String("pipe") - // Unix domain socket - NetworkTransportUnix = NetworkTransportKey.String("unix") -) - -var ( - // IPv4 - NetworkTypeIpv4 = NetworkTypeKey.String("ipv4") - // IPv6 - NetworkTypeIpv6 = NetworkTypeKey.String("ipv6") -) - -// NetworkCarrierIcc returns an attribute KeyValue conforming to the -// "network.carrier.icc" semantic conventions. It represents the ISO 3166-1 -// alpha-2 2-character country code associated with the mobile carrier network. -func NetworkCarrierIcc(val string) attribute.KeyValue { - return NetworkCarrierIccKey.String(val) -} - -// NetworkCarrierMcc returns an attribute KeyValue conforming to the -// "network.carrier.mcc" semantic conventions. It represents the mobile carrier -// country code. -func NetworkCarrierMcc(val string) attribute.KeyValue { - return NetworkCarrierMccKey.String(val) -} - -// NetworkCarrierMnc returns an attribute KeyValue conforming to the -// "network.carrier.mnc" semantic conventions. It represents the mobile carrier -// network code. -func NetworkCarrierMnc(val string) attribute.KeyValue { - return NetworkCarrierMncKey.String(val) -} - -// NetworkCarrierName returns an attribute KeyValue conforming to the -// "network.carrier.name" semantic conventions. It represents the name of the -// mobile carrier. -func NetworkCarrierName(val string) attribute.KeyValue { - return NetworkCarrierNameKey.String(val) -} - -// NetworkLocalAddress returns an attribute KeyValue conforming to the -// "network.local.address" semantic conventions. It represents the local -// address of the network connection - IP address or Unix domain socket name. -func NetworkLocalAddress(val string) attribute.KeyValue { - return NetworkLocalAddressKey.String(val) -} - -// NetworkLocalPort returns an attribute KeyValue conforming to the -// "network.local.port" semantic conventions. It represents the local port -// number of the network connection. -func NetworkLocalPort(val int) attribute.KeyValue { - return NetworkLocalPortKey.Int(val) -} - -// NetworkPeerAddress returns an attribute KeyValue conforming to the -// "network.peer.address" semantic conventions. It represents the peer address -// of the network connection - IP address or Unix domain socket name. -func NetworkPeerAddress(val string) attribute.KeyValue { - return NetworkPeerAddressKey.String(val) -} - -// NetworkPeerPort returns an attribute KeyValue conforming to the -// "network.peer.port" semantic conventions. It represents the peer port number -// of the network connection. -func NetworkPeerPort(val int) attribute.KeyValue { - return NetworkPeerPortKey.Int(val) -} - -// NetworkProtocolName returns an attribute KeyValue conforming to the -// "network.protocol.name" semantic conventions. It represents the [OSI -// application layer](https://osi-model.com/application-layer/) or non-OSI -// equivalent. -func NetworkProtocolName(val string) attribute.KeyValue { - return NetworkProtocolNameKey.String(val) -} - -// NetworkProtocolVersion returns an attribute KeyValue conforming to the -// "network.protocol.version" semantic conventions. It represents the version -// of the protocol specified in `network.protocol.name`. -func NetworkProtocolVersion(val string) attribute.KeyValue { - return NetworkProtocolVersionKey.String(val) -} - -// Attributes for remote procedure calls. -const ( - // RPCConnectRPCErrorCodeKey is the attribute Key conforming to the - // "rpc.connect_rpc.error_code" semantic conventions. It represents the - // [error codes](https://connect.build/docs/protocol/#error-codes) of the - // Connect request. Error codes are always string values. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCConnectRPCErrorCodeKey = attribute.Key("rpc.connect_rpc.error_code") - - // RPCGRPCStatusCodeKey is the attribute Key conforming to the - // "rpc.grpc.status_code" semantic conventions. It represents the [numeric - // status - // code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of - // the gRPC request. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCGRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") - - // RPCJsonrpcErrorCodeKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_code" semantic conventions. It represents the - // `error.code` property of response if it is an error response. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: -32700, 100 - RPCJsonrpcErrorCodeKey = attribute.Key("rpc.jsonrpc.error_code") - - // RPCJsonrpcErrorMessageKey is the attribute Key conforming to the - // "rpc.jsonrpc.error_message" semantic conventions. It represents the - // `error.message` property of response if it is an error response. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Parse error', 'User already exists' - RPCJsonrpcErrorMessageKey = attribute.Key("rpc.jsonrpc.error_message") - - // RPCJsonrpcRequestIDKey is the attribute Key conforming to the - // "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` - // property of request or response. Since protocol allows id to be int, - // string, `null` or missing (for notifications), value is expected to be - // cast to string for simplicity. Use empty string in case of `null` value. - // Omit entirely if this is a notification. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '10', 'request-7', '' - RPCJsonrpcRequestIDKey = attribute.Key("rpc.jsonrpc.request_id") - - // RPCJsonrpcVersionKey is the attribute Key conforming to the - // "rpc.jsonrpc.version" semantic conventions. It represents the protocol - // version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 - // doesn't specify this, the value can be omitted. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2.0', '1.0' - RPCJsonrpcVersionKey = attribute.Key("rpc.jsonrpc.version") - - // RPCMethodKey is the attribute Key conforming to the "rpc.method" - // semantic conventions. It represents the name of the (logical) method - // being called, must be equal to the $method part in the span name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'exampleMethod' - // Note: This is the logical name of the method from the RPC interface - // perspective, which can be different from the name of any implementing - // method/function. The `code.function` attribute may be used to store the - // latter (e.g., method actually executing the call on the server side, RPC - // client stub method on the client side). - RPCMethodKey = attribute.Key("rpc.method") - - // RPCServiceKey is the attribute Key conforming to the "rpc.service" - // semantic conventions. It represents the full (logical) name of the - // service being called, including its package name, if applicable. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myservice.EchoService' - // Note: This is the logical name of the service from the RPC interface - // perspective, which can be different from the name of any implementing - // class. The `code.namespace` attribute may be used to store the latter - // (despite the attribute name, it may include a class name; e.g., class - // with method actually executing the call on the server side, RPC client - // stub class on the client side). - RPCServiceKey = attribute.Key("rpc.service") - - // RPCSystemKey is the attribute Key conforming to the "rpc.system" - // semantic conventions. It represents a string identifying the remoting - // system. See below for a list of well-known identifiers. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - RPCSystemKey = attribute.Key("rpc.system") -) - -var ( - // cancelled - RPCConnectRPCErrorCodeCancelled = RPCConnectRPCErrorCodeKey.String("cancelled") - // unknown - RPCConnectRPCErrorCodeUnknown = RPCConnectRPCErrorCodeKey.String("unknown") - // invalid_argument - RPCConnectRPCErrorCodeInvalidArgument = RPCConnectRPCErrorCodeKey.String("invalid_argument") - // deadline_exceeded - RPCConnectRPCErrorCodeDeadlineExceeded = RPCConnectRPCErrorCodeKey.String("deadline_exceeded") - // not_found - RPCConnectRPCErrorCodeNotFound = RPCConnectRPCErrorCodeKey.String("not_found") - // already_exists - RPCConnectRPCErrorCodeAlreadyExists = RPCConnectRPCErrorCodeKey.String("already_exists") - // permission_denied - RPCConnectRPCErrorCodePermissionDenied = RPCConnectRPCErrorCodeKey.String("permission_denied") - // resource_exhausted - RPCConnectRPCErrorCodeResourceExhausted = RPCConnectRPCErrorCodeKey.String("resource_exhausted") - // failed_precondition - RPCConnectRPCErrorCodeFailedPrecondition = RPCConnectRPCErrorCodeKey.String("failed_precondition") - // aborted - RPCConnectRPCErrorCodeAborted = RPCConnectRPCErrorCodeKey.String("aborted") - // out_of_range - RPCConnectRPCErrorCodeOutOfRange = RPCConnectRPCErrorCodeKey.String("out_of_range") - // unimplemented - RPCConnectRPCErrorCodeUnimplemented = RPCConnectRPCErrorCodeKey.String("unimplemented") - // internal - RPCConnectRPCErrorCodeInternal = RPCConnectRPCErrorCodeKey.String("internal") - // unavailable - RPCConnectRPCErrorCodeUnavailable = RPCConnectRPCErrorCodeKey.String("unavailable") - // data_loss - RPCConnectRPCErrorCodeDataLoss = RPCConnectRPCErrorCodeKey.String("data_loss") - // unauthenticated - RPCConnectRPCErrorCodeUnauthenticated = RPCConnectRPCErrorCodeKey.String("unauthenticated") -) - -var ( - // OK - RPCGRPCStatusCodeOk = RPCGRPCStatusCodeKey.Int(0) - // CANCELLED - RPCGRPCStatusCodeCancelled = RPCGRPCStatusCodeKey.Int(1) - // UNKNOWN - RPCGRPCStatusCodeUnknown = RPCGRPCStatusCodeKey.Int(2) - // INVALID_ARGUMENT - RPCGRPCStatusCodeInvalidArgument = RPCGRPCStatusCodeKey.Int(3) - // DEADLINE_EXCEEDED - RPCGRPCStatusCodeDeadlineExceeded = RPCGRPCStatusCodeKey.Int(4) - // NOT_FOUND - RPCGRPCStatusCodeNotFound = RPCGRPCStatusCodeKey.Int(5) - // ALREADY_EXISTS - RPCGRPCStatusCodeAlreadyExists = RPCGRPCStatusCodeKey.Int(6) - // PERMISSION_DENIED - RPCGRPCStatusCodePermissionDenied = RPCGRPCStatusCodeKey.Int(7) - // RESOURCE_EXHAUSTED - RPCGRPCStatusCodeResourceExhausted = RPCGRPCStatusCodeKey.Int(8) - // FAILED_PRECONDITION - RPCGRPCStatusCodeFailedPrecondition = RPCGRPCStatusCodeKey.Int(9) - // ABORTED - RPCGRPCStatusCodeAborted = RPCGRPCStatusCodeKey.Int(10) - // OUT_OF_RANGE - RPCGRPCStatusCodeOutOfRange = RPCGRPCStatusCodeKey.Int(11) - // UNIMPLEMENTED - RPCGRPCStatusCodeUnimplemented = RPCGRPCStatusCodeKey.Int(12) - // INTERNAL - RPCGRPCStatusCodeInternal = RPCGRPCStatusCodeKey.Int(13) - // UNAVAILABLE - RPCGRPCStatusCodeUnavailable = RPCGRPCStatusCodeKey.Int(14) - // DATA_LOSS - RPCGRPCStatusCodeDataLoss = RPCGRPCStatusCodeKey.Int(15) - // UNAUTHENTICATED - RPCGRPCStatusCodeUnauthenticated = RPCGRPCStatusCodeKey.Int(16) -) - -var ( - // gRPC - RPCSystemGRPC = RPCSystemKey.String("grpc") - // Java RMI - RPCSystemJavaRmi = RPCSystemKey.String("java_rmi") - // .NET WCF - RPCSystemDotnetWcf = RPCSystemKey.String("dotnet_wcf") - // Apache Dubbo - RPCSystemApacheDubbo = RPCSystemKey.String("apache_dubbo") - // Connect RPC - RPCSystemConnectRPC = RPCSystemKey.String("connect_rpc") -) - -// RPCJsonrpcErrorCode returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_code" semantic conventions. It represents the -// `error.code` property of response if it is an error response. -func RPCJsonrpcErrorCode(val int) attribute.KeyValue { - return RPCJsonrpcErrorCodeKey.Int(val) -} - -// RPCJsonrpcErrorMessage returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.error_message" semantic conventions. It represents the -// `error.message` property of response if it is an error response. -func RPCJsonrpcErrorMessage(val string) attribute.KeyValue { - return RPCJsonrpcErrorMessageKey.String(val) -} - -// RPCJsonrpcRequestID returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.request_id" semantic conventions. It represents the `id` -// property of request or response. Since protocol allows id to be int, string, -// `null` or missing (for notifications), value is expected to be cast to -// string for simplicity. Use empty string in case of `null` value. Omit -// entirely if this is a notification. -func RPCJsonrpcRequestID(val string) attribute.KeyValue { - return RPCJsonrpcRequestIDKey.String(val) -} - -// RPCJsonrpcVersion returns an attribute KeyValue conforming to the -// "rpc.jsonrpc.version" semantic conventions. It represents the protocol -// version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 -// doesn't specify this, the value can be omitted. -func RPCJsonrpcVersion(val string) attribute.KeyValue { - return RPCJsonrpcVersionKey.String(val) -} - -// RPCMethod returns an attribute KeyValue conforming to the "rpc.method" -// semantic conventions. It represents the name of the (logical) method being -// called, must be equal to the $method part in the span name. -func RPCMethod(val string) attribute.KeyValue { - return RPCMethodKey.String(val) -} - -// RPCService returns an attribute KeyValue conforming to the "rpc.service" -// semantic conventions. It represents the full (logical) name of the service -// being called, including its package name, if applicable. -func RPCService(val string) attribute.KeyValue { - return RPCServiceKey.String(val) -} - -// These attributes may be used to describe the server in a connection-based -// network interaction where there is one side that initiates the connection -// (the client is the side that initiates the connection). This covers all TCP -// network interactions since TCP is connection-based and one side initiates -// the connection (an exception is made for peer-to-peer communication over TCP -// where the "user-facing" surface of the protocol / API doesn't expose a clear -// notion of client and server). This also covers UDP network interactions -// where one side initiates the interaction, e.g. QUIC (HTTP/3) and DNS. -const ( - // ServerAddressKey is the attribute Key conforming to the "server.address" - // semantic conventions. It represents the server domain name if available - // without reverse DNS lookup; otherwise, IP address or Unix domain socket - // name. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the client side, and when communicating through - // an intermediary, `server.address` SHOULD represent the server address - // behind any intermediaries, for example proxies, if it's available. - ServerAddressKey = attribute.Key("server.address") - - // ServerPortKey is the attribute Key conforming to the "server.port" - // semantic conventions. It represents the server port number. - // - // Type: int - // RequirementLevel: Optional - // Stability: stable - // Examples: 80, 8080, 443 - // Note: When observed from the client side, and when communicating through - // an intermediary, `server.port` SHOULD represent the server port behind - // any intermediaries, for example proxies, if it's available. - ServerPortKey = attribute.Key("server.port") -) - -// ServerAddress returns an attribute KeyValue conforming to the -// "server.address" semantic conventions. It represents the server domain name -// if available without reverse DNS lookup; otherwise, IP address or Unix -// domain socket name. -func ServerAddress(val string) attribute.KeyValue { - return ServerAddressKey.String(val) -} - -// ServerPort returns an attribute KeyValue conforming to the "server.port" -// semantic conventions. It represents the server port number. -func ServerPort(val int) attribute.KeyValue { - return ServerPortKey.Int(val) -} - -// These attributes may be used to describe the sender of a network -// exchange/packet. These should be used when there is no client/server -// relationship between the two sides, or when that relationship is unknown. -// This covers low-level network interactions (e.g. packet tracing) where you -// don't know if there was a connection or which side initiated it. This also -// covers unidirectional UDP flows and peer-to-peer communication where the -// "user-facing" surface of the protocol / API doesn't expose a clear notion of -// client and server. -const ( - // SourceAddressKey is the attribute Key conforming to the "source.address" - // semantic conventions. It represents the source address - domain name if - // available without reverse DNS lookup; otherwise, IP address or Unix - // domain socket name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'source.example.com', '10.1.2.80', '/tmp/my.sock' - // Note: When observed from the destination side, and when communicating - // through an intermediary, `source.address` SHOULD represent the source - // address behind any intermediaries, for example proxies, if it's - // available. - SourceAddressKey = attribute.Key("source.address") - - // SourcePortKey is the attribute Key conforming to the "source.port" - // semantic conventions. It represents the source port number - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3389, 2888 - SourcePortKey = attribute.Key("source.port") -) - -// SourceAddress returns an attribute KeyValue conforming to the -// "source.address" semantic conventions. It represents the source address - -// domain name if available without reverse DNS lookup; otherwise, IP address -// or Unix domain socket name. -func SourceAddress(val string) attribute.KeyValue { - return SourceAddressKey.String(val) -} - -// SourcePort returns an attribute KeyValue conforming to the "source.port" -// semantic conventions. It represents the source port number -func SourcePort(val int) attribute.KeyValue { - return SourcePortKey.Int(val) -} - -// Semantic convention attributes in the TLS namespace. -const ( - // TLSCipherKey is the attribute Key conforming to the "tls.cipher" - // semantic conventions. It represents the string indicating the - // [cipher](https://datatracker.ietf.org/doc/html/rfc5246#appendix-A.5) - // used during the current connection. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'TLS_RSA_WITH_3DES_EDE_CBC_SHA', - // 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256' - // Note: The values allowed for `tls.cipher` MUST be one of the - // `Descriptions` of the [registered TLS Cipher - // Suits](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#table-tls-parameters-4). - TLSCipherKey = attribute.Key("tls.cipher") - - // TLSClientCertificateKey is the attribute Key conforming to the - // "tls.client.certificate" semantic conventions. It represents the - // pEM-encoded stand-alone certificate offered by the client. This is - // usually mutually-exclusive of `client.certificate_chain` since this - // value also exists in that list. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...' - TLSClientCertificateKey = attribute.Key("tls.client.certificate") - - // TLSClientCertificateChainKey is the attribute Key conforming to the - // "tls.client.certificate_chain" semantic conventions. It represents the - // array of PEM-encoded certificates that make up the certificate chain - // offered by the client. This is usually mutually-exclusive of - // `client.certificate` since that value should be the first certificate in - // the chain. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...', 'MI...' - TLSClientCertificateChainKey = attribute.Key("tls.client.certificate_chain") - - // TLSClientHashMd5Key is the attribute Key conforming to the - // "tls.client.hash.md5" semantic conventions. It represents the - // certificate fingerprint using the MD5 digest of DER-encoded version of - // certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0F76C7F2C55BFD7D8E8B8F4BFBF0C9EC' - TLSClientHashMd5Key = attribute.Key("tls.client.hash.md5") - - // TLSClientHashSha1Key is the attribute Key conforming to the - // "tls.client.hash.sha1" semantic conventions. It represents the - // certificate fingerprint using the SHA1 digest of DER-encoded version of - // certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '9E393D93138888D288266C2D915214D1D1CCEB2A' - TLSClientHashSha1Key = attribute.Key("tls.client.hash.sha1") - - // TLSClientHashSha256Key is the attribute Key conforming to the - // "tls.client.hash.sha256" semantic conventions. It represents the - // certificate fingerprint using the SHA256 digest of DER-encoded version - // of certificate offered by the client. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // '0687F666A054EF17A08E2F2162EAB4CBC0D265E1D7875BE74BF3C712CA92DAF0' - TLSClientHashSha256Key = attribute.Key("tls.client.hash.sha256") - - // TLSClientIssuerKey is the attribute Key conforming to the - // "tls.client.issuer" semantic conventions. It represents the - // distinguished name of - // [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) - // of the issuer of the x.509 certificate presented by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=Example Root CA, OU=Infrastructure Team, DC=example, - // DC=com' - TLSClientIssuerKey = attribute.Key("tls.client.issuer") - - // TLSClientJa3Key is the attribute Key conforming to the "tls.client.ja3" - // semantic conventions. It represents a hash that identifies clients based - // on how they perform an SSL/TLS handshake. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'd4e5b18d6b55c71272893221c96ba240' - TLSClientJa3Key = attribute.Key("tls.client.ja3") - - // TLSClientNotAfterKey is the attribute Key conforming to the - // "tls.client.not_after" semantic conventions. It represents the date/Time - // indicating when client certificate is no longer considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021-01-01T00:00:00.000Z' - TLSClientNotAfterKey = attribute.Key("tls.client.not_after") - - // TLSClientNotBeforeKey is the attribute Key conforming to the - // "tls.client.not_before" semantic conventions. It represents the - // date/Time indicating when client certificate is first considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1970-01-01T00:00:00.000Z' - TLSClientNotBeforeKey = attribute.Key("tls.client.not_before") - - // TLSClientServerNameKey is the attribute Key conforming to the - // "tls.client.server_name" semantic conventions. It represents the also - // called an SNI, this tells the server which hostname to which the client - // is attempting to connect to. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry.io' - TLSClientServerNameKey = attribute.Key("tls.client.server_name") - - // TLSClientSubjectKey is the attribute Key conforming to the - // "tls.client.subject" semantic conventions. It represents the - // distinguished name of subject of the x.509 certificate presented by the - // client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=myclient, OU=Documentation Team, DC=example, DC=com' - TLSClientSubjectKey = attribute.Key("tls.client.subject") - - // TLSClientSupportedCiphersKey is the attribute Key conforming to the - // "tls.client.supported_ciphers" semantic conventions. It represents the - // array of ciphers offered by the client during the client hello. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - // "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "..."' - TLSClientSupportedCiphersKey = attribute.Key("tls.client.supported_ciphers") - - // TLSCurveKey is the attribute Key conforming to the "tls.curve" semantic - // conventions. It represents the string indicating the curve used for the - // given cipher, when applicable - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'secp256r1' - TLSCurveKey = attribute.Key("tls.curve") - - // TLSEstablishedKey is the attribute Key conforming to the - // "tls.established" semantic conventions. It represents the boolean flag - // indicating if the TLS negotiation was successful and transitioned to an - // encrypted tunnel. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Examples: True - TLSEstablishedKey = attribute.Key("tls.established") - - // TLSNextProtocolKey is the attribute Key conforming to the - // "tls.next_protocol" semantic conventions. It represents the string - // indicating the protocol being tunneled. Per the values in the [IANA - // registry](https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids), - // this string should be lower case. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'http/1.1' - TLSNextProtocolKey = attribute.Key("tls.next_protocol") - - // TLSProtocolNameKey is the attribute Key conforming to the - // "tls.protocol.name" semantic conventions. It represents the normalized - // lowercase protocol name parsed from original string of the negotiated - // [SSL/TLS protocol - // version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - TLSProtocolNameKey = attribute.Key("tls.protocol.name") - - // TLSProtocolVersionKey is the attribute Key conforming to the - // "tls.protocol.version" semantic conventions. It represents the numeric - // part of the version parsed from the original string of the negotiated - // [SSL/TLS protocol - // version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.2', '3' - TLSProtocolVersionKey = attribute.Key("tls.protocol.version") - - // TLSResumedKey is the attribute Key conforming to the "tls.resumed" - // semantic conventions. It represents the boolean flag indicating if this - // TLS connection was resumed from an existing TLS negotiation. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Examples: True - TLSResumedKey = attribute.Key("tls.resumed") - - // TLSServerCertificateKey is the attribute Key conforming to the - // "tls.server.certificate" semantic conventions. It represents the - // pEM-encoded stand-alone certificate offered by the server. This is - // usually mutually-exclusive of `server.certificate_chain` since this - // value also exists in that list. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...' - TLSServerCertificateKey = attribute.Key("tls.server.certificate") - - // TLSServerCertificateChainKey is the attribute Key conforming to the - // "tls.server.certificate_chain" semantic conventions. It represents the - // array of PEM-encoded certificates that make up the certificate chain - // offered by the server. This is usually mutually-exclusive of - // `server.certificate` since that value should be the first certificate in - // the chain. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'MII...', 'MI...' - TLSServerCertificateChainKey = attribute.Key("tls.server.certificate_chain") - - // TLSServerHashMd5Key is the attribute Key conforming to the - // "tls.server.hash.md5" semantic conventions. It represents the - // certificate fingerprint using the MD5 digest of DER-encoded version of - // certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0F76C7F2C55BFD7D8E8B8F4BFBF0C9EC' - TLSServerHashMd5Key = attribute.Key("tls.server.hash.md5") - - // TLSServerHashSha1Key is the attribute Key conforming to the - // "tls.server.hash.sha1" semantic conventions. It represents the - // certificate fingerprint using the SHA1 digest of DER-encoded version of - // certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '9E393D93138888D288266C2D915214D1D1CCEB2A' - TLSServerHashSha1Key = attribute.Key("tls.server.hash.sha1") - - // TLSServerHashSha256Key is the attribute Key conforming to the - // "tls.server.hash.sha256" semantic conventions. It represents the - // certificate fingerprint using the SHA256 digest of DER-encoded version - // of certificate offered by the server. For consistency with other hash - // values, this value should be formatted as an uppercase hash. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // '0687F666A054EF17A08E2F2162EAB4CBC0D265E1D7875BE74BF3C712CA92DAF0' - TLSServerHashSha256Key = attribute.Key("tls.server.hash.sha256") - - // TLSServerIssuerKey is the attribute Key conforming to the - // "tls.server.issuer" semantic conventions. It represents the - // distinguished name of - // [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) - // of the issuer of the x.509 certificate presented by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=Example Root CA, OU=Infrastructure Team, DC=example, - // DC=com' - TLSServerIssuerKey = attribute.Key("tls.server.issuer") - - // TLSServerJa3sKey is the attribute Key conforming to the - // "tls.server.ja3s" semantic conventions. It represents a hash that - // identifies servers based on how they perform an SSL/TLS handshake. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'd4e5b18d6b55c71272893221c96ba240' - TLSServerJa3sKey = attribute.Key("tls.server.ja3s") - - // TLSServerNotAfterKey is the attribute Key conforming to the - // "tls.server.not_after" semantic conventions. It represents the date/Time - // indicating when server certificate is no longer considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021-01-01T00:00:00.000Z' - TLSServerNotAfterKey = attribute.Key("tls.server.not_after") - - // TLSServerNotBeforeKey is the attribute Key conforming to the - // "tls.server.not_before" semantic conventions. It represents the - // date/Time indicating when server certificate is first considered valid. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1970-01-01T00:00:00.000Z' - TLSServerNotBeforeKey = attribute.Key("tls.server.not_before") - - // TLSServerSubjectKey is the attribute Key conforming to the - // "tls.server.subject" semantic conventions. It represents the - // distinguished name of subject of the x.509 certificate presented by the - // server. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'CN=myserver, OU=Documentation Team, DC=example, DC=com' - TLSServerSubjectKey = attribute.Key("tls.server.subject") -) - -var ( - // ssl - TLSProtocolNameSsl = TLSProtocolNameKey.String("ssl") - // tls - TLSProtocolNameTLS = TLSProtocolNameKey.String("tls") -) - -// TLSCipher returns an attribute KeyValue conforming to the "tls.cipher" -// semantic conventions. It represents the string indicating the -// [cipher](https://datatracker.ietf.org/doc/html/rfc5246#appendix-A.5) used -// during the current connection. -func TLSCipher(val string) attribute.KeyValue { - return TLSCipherKey.String(val) -} - -// TLSClientCertificate returns an attribute KeyValue conforming to the -// "tls.client.certificate" semantic conventions. It represents the pEM-encoded -// stand-alone certificate offered by the client. This is usually -// mutually-exclusive of `client.certificate_chain` since this value also -// exists in that list. -func TLSClientCertificate(val string) attribute.KeyValue { - return TLSClientCertificateKey.String(val) -} - -// TLSClientCertificateChain returns an attribute KeyValue conforming to the -// "tls.client.certificate_chain" semantic conventions. It represents the array -// of PEM-encoded certificates that make up the certificate chain offered by -// the client. This is usually mutually-exclusive of `client.certificate` since -// that value should be the first certificate in the chain. -func TLSClientCertificateChain(val ...string) attribute.KeyValue { - return TLSClientCertificateChainKey.StringSlice(val) -} - -// TLSClientHashMd5 returns an attribute KeyValue conforming to the -// "tls.client.hash.md5" semantic conventions. It represents the certificate -// fingerprint using the MD5 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashMd5(val string) attribute.KeyValue { - return TLSClientHashMd5Key.String(val) -} - -// TLSClientHashSha1 returns an attribute KeyValue conforming to the -// "tls.client.hash.sha1" semantic conventions. It represents the certificate -// fingerprint using the SHA1 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashSha1(val string) attribute.KeyValue { - return TLSClientHashSha1Key.String(val) -} - -// TLSClientHashSha256 returns an attribute KeyValue conforming to the -// "tls.client.hash.sha256" semantic conventions. It represents the certificate -// fingerprint using the SHA256 digest of DER-encoded version of certificate -// offered by the client. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSClientHashSha256(val string) attribute.KeyValue { - return TLSClientHashSha256Key.String(val) -} - -// TLSClientIssuer returns an attribute KeyValue conforming to the -// "tls.client.issuer" semantic conventions. It represents the distinguished -// name of -// [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) of -// the issuer of the x.509 certificate presented by the client. -func TLSClientIssuer(val string) attribute.KeyValue { - return TLSClientIssuerKey.String(val) -} - -// TLSClientJa3 returns an attribute KeyValue conforming to the -// "tls.client.ja3" semantic conventions. It represents a hash that identifies -// clients based on how they perform an SSL/TLS handshake. -func TLSClientJa3(val string) attribute.KeyValue { - return TLSClientJa3Key.String(val) -} - -// TLSClientNotAfter returns an attribute KeyValue conforming to the -// "tls.client.not_after" semantic conventions. It represents the date/Time -// indicating when client certificate is no longer considered valid. -func TLSClientNotAfter(val string) attribute.KeyValue { - return TLSClientNotAfterKey.String(val) -} - -// TLSClientNotBefore returns an attribute KeyValue conforming to the -// "tls.client.not_before" semantic conventions. It represents the date/Time -// indicating when client certificate is first considered valid. -func TLSClientNotBefore(val string) attribute.KeyValue { - return TLSClientNotBeforeKey.String(val) -} - -// TLSClientServerName returns an attribute KeyValue conforming to the -// "tls.client.server_name" semantic conventions. It represents the also called -// an SNI, this tells the server which hostname to which the client is -// attempting to connect to. -func TLSClientServerName(val string) attribute.KeyValue { - return TLSClientServerNameKey.String(val) -} - -// TLSClientSubject returns an attribute KeyValue conforming to the -// "tls.client.subject" semantic conventions. It represents the distinguished -// name of subject of the x.509 certificate presented by the client. -func TLSClientSubject(val string) attribute.KeyValue { - return TLSClientSubjectKey.String(val) -} - -// TLSClientSupportedCiphers returns an attribute KeyValue conforming to the -// "tls.client.supported_ciphers" semantic conventions. It represents the array -// of ciphers offered by the client during the client hello. -func TLSClientSupportedCiphers(val ...string) attribute.KeyValue { - return TLSClientSupportedCiphersKey.StringSlice(val) -} - -// TLSCurve returns an attribute KeyValue conforming to the "tls.curve" -// semantic conventions. It represents the string indicating the curve used for -// the given cipher, when applicable -func TLSCurve(val string) attribute.KeyValue { - return TLSCurveKey.String(val) -} - -// TLSEstablished returns an attribute KeyValue conforming to the -// "tls.established" semantic conventions. It represents the boolean flag -// indicating if the TLS negotiation was successful and transitioned to an -// encrypted tunnel. -func TLSEstablished(val bool) attribute.KeyValue { - return TLSEstablishedKey.Bool(val) -} - -// TLSNextProtocol returns an attribute KeyValue conforming to the -// "tls.next_protocol" semantic conventions. It represents the string -// indicating the protocol being tunneled. Per the values in the [IANA -// registry](https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids), -// this string should be lower case. -func TLSNextProtocol(val string) attribute.KeyValue { - return TLSNextProtocolKey.String(val) -} - -// TLSProtocolVersion returns an attribute KeyValue conforming to the -// "tls.protocol.version" semantic conventions. It represents the numeric part -// of the version parsed from the original string of the negotiated [SSL/TLS -// protocol -// version](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html#RETURN-VALUES) -func TLSProtocolVersion(val string) attribute.KeyValue { - return TLSProtocolVersionKey.String(val) -} - -// TLSResumed returns an attribute KeyValue conforming to the "tls.resumed" -// semantic conventions. It represents the boolean flag indicating if this TLS -// connection was resumed from an existing TLS negotiation. -func TLSResumed(val bool) attribute.KeyValue { - return TLSResumedKey.Bool(val) -} - -// TLSServerCertificate returns an attribute KeyValue conforming to the -// "tls.server.certificate" semantic conventions. It represents the pEM-encoded -// stand-alone certificate offered by the server. This is usually -// mutually-exclusive of `server.certificate_chain` since this value also -// exists in that list. -func TLSServerCertificate(val string) attribute.KeyValue { - return TLSServerCertificateKey.String(val) -} - -// TLSServerCertificateChain returns an attribute KeyValue conforming to the -// "tls.server.certificate_chain" semantic conventions. It represents the array -// of PEM-encoded certificates that make up the certificate chain offered by -// the server. This is usually mutually-exclusive of `server.certificate` since -// that value should be the first certificate in the chain. -func TLSServerCertificateChain(val ...string) attribute.KeyValue { - return TLSServerCertificateChainKey.StringSlice(val) -} - -// TLSServerHashMd5 returns an attribute KeyValue conforming to the -// "tls.server.hash.md5" semantic conventions. It represents the certificate -// fingerprint using the MD5 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashMd5(val string) attribute.KeyValue { - return TLSServerHashMd5Key.String(val) -} - -// TLSServerHashSha1 returns an attribute KeyValue conforming to the -// "tls.server.hash.sha1" semantic conventions. It represents the certificate -// fingerprint using the SHA1 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashSha1(val string) attribute.KeyValue { - return TLSServerHashSha1Key.String(val) -} - -// TLSServerHashSha256 returns an attribute KeyValue conforming to the -// "tls.server.hash.sha256" semantic conventions. It represents the certificate -// fingerprint using the SHA256 digest of DER-encoded version of certificate -// offered by the server. For consistency with other hash values, this value -// should be formatted as an uppercase hash. -func TLSServerHashSha256(val string) attribute.KeyValue { - return TLSServerHashSha256Key.String(val) -} - -// TLSServerIssuer returns an attribute KeyValue conforming to the -// "tls.server.issuer" semantic conventions. It represents the distinguished -// name of -// [subject](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) of -// the issuer of the x.509 certificate presented by the client. -func TLSServerIssuer(val string) attribute.KeyValue { - return TLSServerIssuerKey.String(val) -} - -// TLSServerJa3s returns an attribute KeyValue conforming to the -// "tls.server.ja3s" semantic conventions. It represents a hash that identifies -// servers based on how they perform an SSL/TLS handshake. -func TLSServerJa3s(val string) attribute.KeyValue { - return TLSServerJa3sKey.String(val) -} - -// TLSServerNotAfter returns an attribute KeyValue conforming to the -// "tls.server.not_after" semantic conventions. It represents the date/Time -// indicating when server certificate is no longer considered valid. -func TLSServerNotAfter(val string) attribute.KeyValue { - return TLSServerNotAfterKey.String(val) -} - -// TLSServerNotBefore returns an attribute KeyValue conforming to the -// "tls.server.not_before" semantic conventions. It represents the date/Time -// indicating when server certificate is first considered valid. -func TLSServerNotBefore(val string) attribute.KeyValue { - return TLSServerNotBeforeKey.String(val) -} - -// TLSServerSubject returns an attribute KeyValue conforming to the -// "tls.server.subject" semantic conventions. It represents the distinguished -// name of subject of the x.509 certificate presented by the server. -func TLSServerSubject(val string) attribute.KeyValue { - return TLSServerSubjectKey.String(val) -} - -// Attributes describing URL. -const ( - // URLFragmentKey is the attribute Key conforming to the "url.fragment" - // semantic conventions. It represents the [URI - // fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'SemConv' - URLFragmentKey = attribute.Key("url.fragment") - - // URLFullKey is the attribute Key conforming to the "url.full" semantic - // conventions. It represents the absolute URL describing a network - // resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'https://www.foo.bar/search?q=OpenTelemetry#SemConv', - // '//localhost' - // Note: For network calls, URL usually has - // `scheme://host[:port][path][?query][#fragment]` format, where the - // fragment is not transmitted over HTTP, but if it is known, it SHOULD be - // included nevertheless. - // `url.full` MUST NOT contain credentials passed via URL in form of - // `https://username:password@www.example.com/`. In such case username and - // password SHOULD be redacted and attribute's value SHOULD be - // `https://REDACTED:REDACTED@www.example.com/`. - // `url.full` SHOULD capture the absolute URL when it is available (or can - // be reconstructed) and SHOULD NOT be validated or modified except for - // sanitizing purposes. - URLFullKey = attribute.Key("url.full") - - // URLPathKey is the attribute Key conforming to the "url.path" semantic - // conventions. It represents the [URI - // path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: '/search' - URLPathKey = attribute.Key("url.path") - - // URLQueryKey is the attribute Key conforming to the "url.query" semantic - // conventions. It represents the [URI - // query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'q=OpenTelemetry' - // Note: Sensitive content provided in query string SHOULD be scrubbed when - // instrumentations can identify it. - URLQueryKey = attribute.Key("url.query") - - // URLSchemeKey is the attribute Key conforming to the "url.scheme" - // semantic conventions. It represents the [URI - // scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component - // identifying the used protocol. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'https', 'ftp', 'telnet' - URLSchemeKey = attribute.Key("url.scheme") -) - -// URLFragment returns an attribute KeyValue conforming to the -// "url.fragment" semantic conventions. It represents the [URI -// fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component -func URLFragment(val string) attribute.KeyValue { - return URLFragmentKey.String(val) -} - -// URLFull returns an attribute KeyValue conforming to the "url.full" -// semantic conventions. It represents the absolute URL describing a network -// resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) -func URLFull(val string) attribute.KeyValue { - return URLFullKey.String(val) -} - -// URLPath returns an attribute KeyValue conforming to the "url.path" -// semantic conventions. It represents the [URI -// path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component -func URLPath(val string) attribute.KeyValue { - return URLPathKey.String(val) -} - -// URLQuery returns an attribute KeyValue conforming to the "url.query" -// semantic conventions. It represents the [URI -// query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component -func URLQuery(val string) attribute.KeyValue { - return URLQueryKey.String(val) -} - -// URLScheme returns an attribute KeyValue conforming to the "url.scheme" -// semantic conventions. It represents the [URI -// scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component -// identifying the used protocol. -func URLScheme(val string) attribute.KeyValue { - return URLSchemeKey.String(val) -} - -// Describes user-agent attributes. -const ( - // UserAgentOriginalKey is the attribute Key conforming to the - // "user_agent.original" semantic conventions. It represents the value of - // the [HTTP - // User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) - // header sent by the client. - // - // Type: string - // RequirementLevel: Optional - // Stability: stable - // Examples: 'CERN-LineMode/2.15 libwww/2.17b3', 'Mozilla/5.0 (iPhone; CPU - // iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) - // Version/14.1.2 Mobile/15E148 Safari/604.1' - UserAgentOriginalKey = attribute.Key("user_agent.original") -) - -// UserAgentOriginal returns an attribute KeyValue conforming to the -// "user_agent.original" semantic conventions. It represents the value of the -// [HTTP -// User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) -// header sent by the client. -func UserAgentOriginal(val string) attribute.KeyValue { - return UserAgentOriginalKey.String(val) -} - -// Session is defined as the period of time encompassing all activities -// performed by the application and the actions executed by the end user. -// Consequently, a Session is represented as a collection of Logs, Events, and -// Spans emitted by the Client Application throughout the Session's duration. -// Each Session is assigned a unique identifier, which is included as an -// attribute in the Logs, Events, and Spans generated during the Session's -// lifecycle. -// When a session reaches end of life, typically due to user inactivity or -// session timeout, a new session identifier will be assigned. The previous -// session identifier may be provided by the instrumentation so that telemetry -// backends can link the two sessions. -const ( - // SessionIDKey is the attribute Key conforming to the "session.id" - // semantic conventions. It represents a unique id to identify a session. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '00112233-4455-6677-8899-aabbccddeeff' - SessionIDKey = attribute.Key("session.id") - - // SessionPreviousIDKey is the attribute Key conforming to the - // "session.previous_id" semantic conventions. It represents the previous - // `session.id` for this user, when known. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '00112233-4455-6677-8899-aabbccddeeff' - SessionPreviousIDKey = attribute.Key("session.previous_id") -) - -// SessionID returns an attribute KeyValue conforming to the "session.id" -// semantic conventions. It represents a unique id to identify a session. -func SessionID(val string) attribute.KeyValue { - return SessionIDKey.String(val) -} - -// SessionPreviousID returns an attribute KeyValue conforming to the -// "session.previous_id" semantic conventions. It represents the previous -// `session.id` for this user, when known. -func SessionPreviousID(val string) attribute.KeyValue { - return SessionPreviousIDKey.String(val) -} diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go deleted file mode 100644 index d27e8a8f8..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package semconv implements OpenTelemetry semantic conventions. -// -// OpenTelemetry semantic conventions are agreed standardized naming -// patterns for OpenTelemetry things. This package represents the v1.24.0 -// version of the OpenTelemetry semantic conventions. -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go deleted file mode 100644 index 6c019aafc..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -import "go.opentelemetry.io/otel/attribute" - -// This event represents an occurrence of a lifecycle transition on the iOS -// platform. -const ( - // IosStateKey is the attribute Key conforming to the "ios.state" semantic - // conventions. It represents the this attribute represents the state the - // application has transitioned into at the occurrence of the event. - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - // Note: The iOS lifecycle states are defined in the [UIApplicationDelegate - // documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate#1656902), - // and from which the `OS terminology` column values are derived. - IosStateKey = attribute.Key("ios.state") -) - -var ( - // The app has become `active`. Associated with UIKit notification `applicationDidBecomeActive` - IosStateActive = IosStateKey.String("active") - // The app is now `inactive`. Associated with UIKit notification `applicationWillResignActive` - IosStateInactive = IosStateKey.String("inactive") - // The app is now in the background. This value is associated with UIKit notification `applicationDidEnterBackground` - IosStateBackground = IosStateKey.String("background") - // The app is now in the foreground. This value is associated with UIKit notification `applicationWillEnterForeground` - IosStateForeground = IosStateKey.String("foreground") - // The app is about to terminate. Associated with UIKit notification `applicationWillTerminate` - IosStateTerminate = IosStateKey.String("terminate") -) - -// This event represents an occurrence of a lifecycle transition on the Android -// platform. -const ( - // AndroidStateKey is the attribute Key conforming to the "android.state" - // semantic conventions. It represents the this attribute represents the - // state the application has transitioned into at the occurrence of the - // event. - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - // Note: The Android lifecycle states are defined in [Activity lifecycle - // callbacks](https://developer.android.com/guide/components/activities/activity-lifecycle#lc), - // and from which the `OS identifiers` are derived. - AndroidStateKey = attribute.Key("android.state") -) - -var ( - // Any time before Activity.onResume() or, if the app has no Activity, Context.startService() has been called in the app for the first time - AndroidStateCreated = AndroidStateKey.String("created") - // Any time after Activity.onPause() or, if the app has no Activity, Context.stopService() has been called when the app was in the foreground state - AndroidStateBackground = AndroidStateKey.String("background") - // Any time after Activity.onResume() or, if the app has no Activity, Context.startService() has been called when the app was in either the created or background states - AndroidStateForeground = AndroidStateKey.String("foreground") -) - -// This semantic convention defines the attributes used to represent a feature -// flag evaluation as an event. -const ( - // FeatureFlagKeyKey is the attribute Key conforming to the - // "feature_flag.key" semantic conventions. It represents the unique - // identifier of the feature flag. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'logo-color' - FeatureFlagKeyKey = attribute.Key("feature_flag.key") - - // FeatureFlagProviderNameKey is the attribute Key conforming to the - // "feature_flag.provider_name" semantic conventions. It represents the - // name of the service provider that performs the flag evaluation. - // - // Type: string - // RequirementLevel: Recommended - // Stability: experimental - // Examples: 'Flag Manager' - FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") - - // FeatureFlagVariantKey is the attribute Key conforming to the - // "feature_flag.variant" semantic conventions. It represents the sHOULD be - // a semantic identifier for a value. If one is unavailable, a stringified - // version of the value can be used. - // - // Type: string - // RequirementLevel: Recommended - // Stability: experimental - // Examples: 'red', 'true', 'on' - // Note: A semantic identifier, commonly referred to as a variant, provides - // a means - // for referring to a value without including the value itself. This can - // provide additional context for understanding the meaning behind a value. - // For example, the variant `red` maybe be used for the value `#c05543`. - // - // A stringified version of the value can be used in situations where a - // semantic identifier is unavailable. String representation of the value - // should be determined by the implementer. - FeatureFlagVariantKey = attribute.Key("feature_flag.variant") -) - -// FeatureFlagKey returns an attribute KeyValue conforming to the -// "feature_flag.key" semantic conventions. It represents the unique identifier -// of the feature flag. -func FeatureFlagKey(val string) attribute.KeyValue { - return FeatureFlagKeyKey.String(val) -} - -// FeatureFlagProviderName returns an attribute KeyValue conforming to the -// "feature_flag.provider_name" semantic conventions. It represents the name of -// the service provider that performs the flag evaluation. -func FeatureFlagProviderName(val string) attribute.KeyValue { - return FeatureFlagProviderNameKey.String(val) -} - -// FeatureFlagVariant returns an attribute KeyValue conforming to the -// "feature_flag.variant" semantic conventions. It represents the sHOULD be a -// semantic identifier for a value. If one is unavailable, a stringified -// version of the value can be used. -func FeatureFlagVariant(val string) attribute.KeyValue { - return FeatureFlagVariantKey.String(val) -} - -// RPC received/sent message. -const ( - // MessageCompressedSizeKey is the attribute Key conforming to the - // "message.compressed_size" semantic conventions. It represents the - // compressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - MessageCompressedSizeKey = attribute.Key("message.compressed_size") - - // MessageIDKey is the attribute Key conforming to the "message.id" - // semantic conventions. It represents the mUST be calculated as two - // different counters starting from `1` one for sent messages and one for - // received message. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Note: This way we guarantee that the values will be consistent between - // different implementations. - MessageIDKey = attribute.Key("message.id") - - // MessageTypeKey is the attribute Key conforming to the "message.type" - // semantic conventions. It represents the whether this is a received or - // sent message. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - MessageTypeKey = attribute.Key("message.type") - - // MessageUncompressedSizeKey is the attribute Key conforming to the - // "message.uncompressed_size" semantic conventions. It represents the - // uncompressed size of the message in bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - MessageUncompressedSizeKey = attribute.Key("message.uncompressed_size") -) - -var ( - // sent - MessageTypeSent = MessageTypeKey.String("SENT") - // received - MessageTypeReceived = MessageTypeKey.String("RECEIVED") -) - -// MessageCompressedSize returns an attribute KeyValue conforming to the -// "message.compressed_size" semantic conventions. It represents the compressed -// size of the message in bytes. -func MessageCompressedSize(val int) attribute.KeyValue { - return MessageCompressedSizeKey.Int(val) -} - -// MessageID returns an attribute KeyValue conforming to the "message.id" -// semantic conventions. It represents the mUST be calculated as two different -// counters starting from `1` one for sent messages and one for received -// message. -func MessageID(val int) attribute.KeyValue { - return MessageIDKey.Int(val) -} - -// MessageUncompressedSize returns an attribute KeyValue conforming to the -// "message.uncompressed_size" semantic conventions. It represents the -// uncompressed size of the message in bytes. -func MessageUncompressedSize(val int) attribute.KeyValue { - return MessageUncompressedSizeKey.Int(val) -} diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go deleted file mode 100644 index 7235bb51d..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -const ( - // ExceptionEventName is the name of the Span event representing an exception. - ExceptionEventName = "exception" -) diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go deleted file mode 100644 index a6b953f62..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go +++ /dev/null @@ -1,1071 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -const ( - - // DBClientConnectionsUsage is the metric conforming to the - // "db.client.connections.usage" semantic conventions. It represents the number - // of connections that are currently in state described by the `state` - // attribute. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsUsageName = "db.client.connections.usage" - DBClientConnectionsUsageUnit = "{connection}" - DBClientConnectionsUsageDescription = "The number of connections that are currently in state described by the `state` attribute" - - // DBClientConnectionsIdleMax is the metric conforming to the - // "db.client.connections.idle.max" semantic conventions. It represents the - // maximum number of idle open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsIdleMaxName = "db.client.connections.idle.max" - DBClientConnectionsIdleMaxUnit = "{connection}" - DBClientConnectionsIdleMaxDescription = "The maximum number of idle open connections allowed" - - // DBClientConnectionsIdleMin is the metric conforming to the - // "db.client.connections.idle.min" semantic conventions. It represents the - // minimum number of idle open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsIdleMinName = "db.client.connections.idle.min" - DBClientConnectionsIdleMinUnit = "{connection}" - DBClientConnectionsIdleMinDescription = "The minimum number of idle open connections allowed" - - // DBClientConnectionsMax is the metric conforming to the - // "db.client.connections.max" semantic conventions. It represents the maximum - // number of open connections allowed. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - DBClientConnectionsMaxName = "db.client.connections.max" - DBClientConnectionsMaxUnit = "{connection}" - DBClientConnectionsMaxDescription = "The maximum number of open connections allowed" - - // DBClientConnectionsPendingRequests is the metric conforming to the - // "db.client.connections.pending_requests" semantic conventions. It represents - // the number of pending requests for an open connection, cumulative for the - // entire pool. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - DBClientConnectionsPendingRequestsName = "db.client.connections.pending_requests" - DBClientConnectionsPendingRequestsUnit = "{request}" - DBClientConnectionsPendingRequestsDescription = "The number of pending requests for an open connection, cumulative for the entire pool" - - // DBClientConnectionsTimeouts is the metric conforming to the - // "db.client.connections.timeouts" semantic conventions. It represents the - // number of connection timeouts that have occurred trying to obtain a - // connection from the pool. - // Instrument: counter - // Unit: {timeout} - // Stability: Experimental - DBClientConnectionsTimeoutsName = "db.client.connections.timeouts" - DBClientConnectionsTimeoutsUnit = "{timeout}" - DBClientConnectionsTimeoutsDescription = "The number of connection timeouts that have occurred trying to obtain a connection from the pool" - - // DBClientConnectionsCreateTime is the metric conforming to the - // "db.client.connections.create_time" semantic conventions. It represents the - // time it took to create a new connection. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsCreateTimeName = "db.client.connections.create_time" - DBClientConnectionsCreateTimeUnit = "ms" - DBClientConnectionsCreateTimeDescription = "The time it took to create a new connection" - - // DBClientConnectionsWaitTime is the metric conforming to the - // "db.client.connections.wait_time" semantic conventions. It represents the - // time it took to obtain an open connection from the pool. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsWaitTimeName = "db.client.connections.wait_time" - DBClientConnectionsWaitTimeUnit = "ms" - DBClientConnectionsWaitTimeDescription = "The time it took to obtain an open connection from the pool" - - // DBClientConnectionsUseTime is the metric conforming to the - // "db.client.connections.use_time" semantic conventions. It represents the - // time between borrowing a connection and returning it to the pool. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - DBClientConnectionsUseTimeName = "db.client.connections.use_time" - DBClientConnectionsUseTimeUnit = "ms" - DBClientConnectionsUseTimeDescription = "The time between borrowing a connection and returning it to the pool" - - // AspnetcoreRoutingMatchAttempts is the metric conforming to the - // "aspnetcore.routing.match_attempts" semantic conventions. It represents the - // number of requests that were attempted to be matched to an endpoint. - // Instrument: counter - // Unit: {match_attempt} - // Stability: Experimental - AspnetcoreRoutingMatchAttemptsName = "aspnetcore.routing.match_attempts" - AspnetcoreRoutingMatchAttemptsUnit = "{match_attempt}" - AspnetcoreRoutingMatchAttemptsDescription = "Number of requests that were attempted to be matched to an endpoint." - - // AspnetcoreDiagnosticsExceptions is the metric conforming to the - // "aspnetcore.diagnostics.exceptions" semantic conventions. It represents the - // number of exceptions caught by exception handling middleware. - // Instrument: counter - // Unit: {exception} - // Stability: Experimental - AspnetcoreDiagnosticsExceptionsName = "aspnetcore.diagnostics.exceptions" - AspnetcoreDiagnosticsExceptionsUnit = "{exception}" - AspnetcoreDiagnosticsExceptionsDescription = "Number of exceptions caught by exception handling middleware." - - // AspnetcoreRateLimitingActiveRequestLeases is the metric conforming to the - // "aspnetcore.rate_limiting.active_request_leases" semantic conventions. It - // represents the number of requests that are currently active on the server - // that hold a rate limiting lease. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - AspnetcoreRateLimitingActiveRequestLeasesName = "aspnetcore.rate_limiting.active_request_leases" - AspnetcoreRateLimitingActiveRequestLeasesUnit = "{request}" - AspnetcoreRateLimitingActiveRequestLeasesDescription = "Number of requests that are currently active on the server that hold a rate limiting lease." - - // AspnetcoreRateLimitingRequestLeaseDuration is the metric conforming to the - // "aspnetcore.rate_limiting.request_lease.duration" semantic conventions. It - // represents the duration of rate limiting lease held by requests on the - // server. - // Instrument: histogram - // Unit: s - // Stability: Experimental - AspnetcoreRateLimitingRequestLeaseDurationName = "aspnetcore.rate_limiting.request_lease.duration" - AspnetcoreRateLimitingRequestLeaseDurationUnit = "s" - AspnetcoreRateLimitingRequestLeaseDurationDescription = "The duration of rate limiting lease held by requests on the server." - - // AspnetcoreRateLimitingRequestTimeInQueue is the metric conforming to the - // "aspnetcore.rate_limiting.request.time_in_queue" semantic conventions. It - // represents the time the request spent in a queue waiting to acquire a rate - // limiting lease. - // Instrument: histogram - // Unit: s - // Stability: Experimental - AspnetcoreRateLimitingRequestTimeInQueueName = "aspnetcore.rate_limiting.request.time_in_queue" - AspnetcoreRateLimitingRequestTimeInQueueUnit = "s" - AspnetcoreRateLimitingRequestTimeInQueueDescription = "The time the request spent in a queue waiting to acquire a rate limiting lease." - - // AspnetcoreRateLimitingQueuedRequests is the metric conforming to the - // "aspnetcore.rate_limiting.queued_requests" semantic conventions. It - // represents the number of requests that are currently queued, waiting to - // acquire a rate limiting lease. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - AspnetcoreRateLimitingQueuedRequestsName = "aspnetcore.rate_limiting.queued_requests" - AspnetcoreRateLimitingQueuedRequestsUnit = "{request}" - AspnetcoreRateLimitingQueuedRequestsDescription = "Number of requests that are currently queued, waiting to acquire a rate limiting lease." - - // AspnetcoreRateLimitingRequests is the metric conforming to the - // "aspnetcore.rate_limiting.requests" semantic conventions. It represents the - // number of requests that tried to acquire a rate limiting lease. - // Instrument: counter - // Unit: {request} - // Stability: Experimental - AspnetcoreRateLimitingRequestsName = "aspnetcore.rate_limiting.requests" - AspnetcoreRateLimitingRequestsUnit = "{request}" - AspnetcoreRateLimitingRequestsDescription = "Number of requests that tried to acquire a rate limiting lease." - - // DNSLookupDuration is the metric conforming to the "dns.lookup.duration" - // semantic conventions. It represents the measures the time taken to perform a - // DNS lookup. - // Instrument: histogram - // Unit: s - // Stability: Experimental - DNSLookupDurationName = "dns.lookup.duration" - DNSLookupDurationUnit = "s" - DNSLookupDurationDescription = "Measures the time taken to perform a DNS lookup." - - // HTTPClientOpenConnections is the metric conforming to the - // "http.client.open_connections" semantic conventions. It represents the - // number of outbound HTTP connections that are currently active or idle on the - // client. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - HTTPClientOpenConnectionsName = "http.client.open_connections" - HTTPClientOpenConnectionsUnit = "{connection}" - HTTPClientOpenConnectionsDescription = "Number of outbound HTTP connections that are currently active or idle on the client." - - // HTTPClientConnectionDuration is the metric conforming to the - // "http.client.connection.duration" semantic conventions. It represents the - // duration of the successfully established outbound HTTP connections. - // Instrument: histogram - // Unit: s - // Stability: Experimental - HTTPClientConnectionDurationName = "http.client.connection.duration" - HTTPClientConnectionDurationUnit = "s" - HTTPClientConnectionDurationDescription = "The duration of the successfully established outbound HTTP connections." - - // HTTPClientActiveRequests is the metric conforming to the - // "http.client.active_requests" semantic conventions. It represents the number - // of active HTTP requests. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - HTTPClientActiveRequestsName = "http.client.active_requests" - HTTPClientActiveRequestsUnit = "{request}" - HTTPClientActiveRequestsDescription = "Number of active HTTP requests." - - // HTTPClientRequestTimeInQueue is the metric conforming to the - // "http.client.request.time_in_queue" semantic conventions. It represents the - // amount of time requests spent on a queue waiting for an available - // connection. - // Instrument: histogram - // Unit: s - // Stability: Experimental - HTTPClientRequestTimeInQueueName = "http.client.request.time_in_queue" - HTTPClientRequestTimeInQueueUnit = "s" - HTTPClientRequestTimeInQueueDescription = "The amount of time requests spent on a queue waiting for an available connection." - - // KestrelActiveConnections is the metric conforming to the - // "kestrel.active_connections" semantic conventions. It represents the number - // of connections that are currently active on the server. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - KestrelActiveConnectionsName = "kestrel.active_connections" - KestrelActiveConnectionsUnit = "{connection}" - KestrelActiveConnectionsDescription = "Number of connections that are currently active on the server." - - // KestrelConnectionDuration is the metric conforming to the - // "kestrel.connection.duration" semantic conventions. It represents the - // duration of connections on the server. - // Instrument: histogram - // Unit: s - // Stability: Experimental - KestrelConnectionDurationName = "kestrel.connection.duration" - KestrelConnectionDurationUnit = "s" - KestrelConnectionDurationDescription = "The duration of connections on the server." - - // KestrelRejectedConnections is the metric conforming to the - // "kestrel.rejected_connections" semantic conventions. It represents the - // number of connections rejected by the server. - // Instrument: counter - // Unit: {connection} - // Stability: Experimental - KestrelRejectedConnectionsName = "kestrel.rejected_connections" - KestrelRejectedConnectionsUnit = "{connection}" - KestrelRejectedConnectionsDescription = "Number of connections rejected by the server." - - // KestrelQueuedConnections is the metric conforming to the - // "kestrel.queued_connections" semantic conventions. It represents the number - // of connections that are currently queued and are waiting to start. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - KestrelQueuedConnectionsName = "kestrel.queued_connections" - KestrelQueuedConnectionsUnit = "{connection}" - KestrelQueuedConnectionsDescription = "Number of connections that are currently queued and are waiting to start." - - // KestrelQueuedRequests is the metric conforming to the - // "kestrel.queued_requests" semantic conventions. It represents the number of - // HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are - // currently queued and are waiting to start. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - KestrelQueuedRequestsName = "kestrel.queued_requests" - KestrelQueuedRequestsUnit = "{request}" - KestrelQueuedRequestsDescription = "Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start." - - // KestrelUpgradedConnections is the metric conforming to the - // "kestrel.upgraded_connections" semantic conventions. It represents the - // number of connections that are currently upgraded (WebSockets). . - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - KestrelUpgradedConnectionsName = "kestrel.upgraded_connections" - KestrelUpgradedConnectionsUnit = "{connection}" - KestrelUpgradedConnectionsDescription = "Number of connections that are currently upgraded (WebSockets). ." - - // KestrelTLSHandshakeDuration is the metric conforming to the - // "kestrel.tls_handshake.duration" semantic conventions. It represents the - // duration of TLS handshakes on the server. - // Instrument: histogram - // Unit: s - // Stability: Experimental - KestrelTLSHandshakeDurationName = "kestrel.tls_handshake.duration" - KestrelTLSHandshakeDurationUnit = "s" - KestrelTLSHandshakeDurationDescription = "The duration of TLS handshakes on the server." - - // KestrelActiveTLSHandshakes is the metric conforming to the - // "kestrel.active_tls_handshakes" semantic conventions. It represents the - // number of TLS handshakes that are currently in progress on the server. - // Instrument: updowncounter - // Unit: {handshake} - // Stability: Experimental - KestrelActiveTLSHandshakesName = "kestrel.active_tls_handshakes" - KestrelActiveTLSHandshakesUnit = "{handshake}" - KestrelActiveTLSHandshakesDescription = "Number of TLS handshakes that are currently in progress on the server." - - // SignalrServerConnectionDuration is the metric conforming to the - // "signalr.server.connection.duration" semantic conventions. It represents the - // duration of connections on the server. - // Instrument: histogram - // Unit: s - // Stability: Experimental - SignalrServerConnectionDurationName = "signalr.server.connection.duration" - SignalrServerConnectionDurationUnit = "s" - SignalrServerConnectionDurationDescription = "The duration of connections on the server." - - // SignalrServerActiveConnections is the metric conforming to the - // "signalr.server.active_connections" semantic conventions. It represents the - // number of connections that are currently active on the server. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - SignalrServerActiveConnectionsName = "signalr.server.active_connections" - SignalrServerActiveConnectionsUnit = "{connection}" - SignalrServerActiveConnectionsDescription = "Number of connections that are currently active on the server." - - // FaaSInvokeDuration is the metric conforming to the "faas.invoke_duration" - // semantic conventions. It represents the measures the duration of the - // function's logic execution. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSInvokeDurationName = "faas.invoke_duration" - FaaSInvokeDurationUnit = "s" - FaaSInvokeDurationDescription = "Measures the duration of the function's logic execution" - - // FaaSInitDuration is the metric conforming to the "faas.init_duration" - // semantic conventions. It represents the measures the duration of the - // function's initialization, such as a cold start. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSInitDurationName = "faas.init_duration" - FaaSInitDurationUnit = "s" - FaaSInitDurationDescription = "Measures the duration of the function's initialization, such as a cold start" - - // FaaSColdstarts is the metric conforming to the "faas.coldstarts" semantic - // conventions. It represents the number of invocation cold starts. - // Instrument: counter - // Unit: {coldstart} - // Stability: Experimental - FaaSColdstartsName = "faas.coldstarts" - FaaSColdstartsUnit = "{coldstart}" - FaaSColdstartsDescription = "Number of invocation cold starts" - - // FaaSErrors is the metric conforming to the "faas.errors" semantic - // conventions. It represents the number of invocation errors. - // Instrument: counter - // Unit: {error} - // Stability: Experimental - FaaSErrorsName = "faas.errors" - FaaSErrorsUnit = "{error}" - FaaSErrorsDescription = "Number of invocation errors" - - // FaaSInvocations is the metric conforming to the "faas.invocations" semantic - // conventions. It represents the number of successful invocations. - // Instrument: counter - // Unit: {invocation} - // Stability: Experimental - FaaSInvocationsName = "faas.invocations" - FaaSInvocationsUnit = "{invocation}" - FaaSInvocationsDescription = "Number of successful invocations" - - // FaaSTimeouts is the metric conforming to the "faas.timeouts" semantic - // conventions. It represents the number of invocation timeouts. - // Instrument: counter - // Unit: {timeout} - // Stability: Experimental - FaaSTimeoutsName = "faas.timeouts" - FaaSTimeoutsUnit = "{timeout}" - FaaSTimeoutsDescription = "Number of invocation timeouts" - - // FaaSMemUsage is the metric conforming to the "faas.mem_usage" semantic - // conventions. It represents the distribution of max memory usage per - // invocation. - // Instrument: histogram - // Unit: By - // Stability: Experimental - FaaSMemUsageName = "faas.mem_usage" - FaaSMemUsageUnit = "By" - FaaSMemUsageDescription = "Distribution of max memory usage per invocation" - - // FaaSCPUUsage is the metric conforming to the "faas.cpu_usage" semantic - // conventions. It represents the distribution of CPU usage per invocation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - FaaSCPUUsageName = "faas.cpu_usage" - FaaSCPUUsageUnit = "s" - FaaSCPUUsageDescription = "Distribution of CPU usage per invocation" - - // FaaSNetIo is the metric conforming to the "faas.net_io" semantic - // conventions. It represents the distribution of net I/O usage per invocation. - // Instrument: histogram - // Unit: By - // Stability: Experimental - FaaSNetIoName = "faas.net_io" - FaaSNetIoUnit = "By" - FaaSNetIoDescription = "Distribution of net I/O usage per invocation" - - // HTTPServerRequestDuration is the metric conforming to the - // "http.server.request.duration" semantic conventions. It represents the - // duration of HTTP server requests. - // Instrument: histogram - // Unit: s - // Stability: Stable - HTTPServerRequestDurationName = "http.server.request.duration" - HTTPServerRequestDurationUnit = "s" - HTTPServerRequestDurationDescription = "Duration of HTTP server requests." - - // HTTPServerActiveRequests is the metric conforming to the - // "http.server.active_requests" semantic conventions. It represents the number - // of active HTTP server requests. - // Instrument: updowncounter - // Unit: {request} - // Stability: Experimental - HTTPServerActiveRequestsName = "http.server.active_requests" - HTTPServerActiveRequestsUnit = "{request}" - HTTPServerActiveRequestsDescription = "Number of active HTTP server requests." - - // HTTPServerRequestBodySize is the metric conforming to the - // "http.server.request.body.size" semantic conventions. It represents the size - // of HTTP server request bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPServerRequestBodySizeName = "http.server.request.body.size" - HTTPServerRequestBodySizeUnit = "By" - HTTPServerRequestBodySizeDescription = "Size of HTTP server request bodies." - - // HTTPServerResponseBodySize is the metric conforming to the - // "http.server.response.body.size" semantic conventions. It represents the - // size of HTTP server response bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPServerResponseBodySizeName = "http.server.response.body.size" - HTTPServerResponseBodySizeUnit = "By" - HTTPServerResponseBodySizeDescription = "Size of HTTP server response bodies." - - // HTTPClientRequestDuration is the metric conforming to the - // "http.client.request.duration" semantic conventions. It represents the - // duration of HTTP client requests. - // Instrument: histogram - // Unit: s - // Stability: Stable - HTTPClientRequestDurationName = "http.client.request.duration" - HTTPClientRequestDurationUnit = "s" - HTTPClientRequestDurationDescription = "Duration of HTTP client requests." - - // HTTPClientRequestBodySize is the metric conforming to the - // "http.client.request.body.size" semantic conventions. It represents the size - // of HTTP client request bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPClientRequestBodySizeName = "http.client.request.body.size" - HTTPClientRequestBodySizeUnit = "By" - HTTPClientRequestBodySizeDescription = "Size of HTTP client request bodies." - - // HTTPClientResponseBodySize is the metric conforming to the - // "http.client.response.body.size" semantic conventions. It represents the - // size of HTTP client response bodies. - // Instrument: histogram - // Unit: By - // Stability: Experimental - HTTPClientResponseBodySizeName = "http.client.response.body.size" - HTTPClientResponseBodySizeUnit = "By" - HTTPClientResponseBodySizeDescription = "Size of HTTP client response bodies." - - // JvmMemoryInit is the metric conforming to the "jvm.memory.init" semantic - // conventions. It represents the measure of initial memory requested. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmMemoryInitName = "jvm.memory.init" - JvmMemoryInitUnit = "By" - JvmMemoryInitDescription = "Measure of initial memory requested." - - // JvmSystemCPUUtilization is the metric conforming to the - // "jvm.system.cpu.utilization" semantic conventions. It represents the recent - // CPU utilization for the whole system as reported by the JVM. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - JvmSystemCPUUtilizationName = "jvm.system.cpu.utilization" - JvmSystemCPUUtilizationUnit = "1" - JvmSystemCPUUtilizationDescription = "Recent CPU utilization for the whole system as reported by the JVM." - - // JvmSystemCPULoad1m is the metric conforming to the "jvm.system.cpu.load_1m" - // semantic conventions. It represents the average CPU load of the whole system - // for the last minute as reported by the JVM. - // Instrument: gauge - // Unit: {run_queue_item} - // Stability: Experimental - JvmSystemCPULoad1mName = "jvm.system.cpu.load_1m" - JvmSystemCPULoad1mUnit = "{run_queue_item}" - JvmSystemCPULoad1mDescription = "Average CPU load of the whole system for the last minute as reported by the JVM." - - // JvmBufferMemoryUsage is the metric conforming to the - // "jvm.buffer.memory.usage" semantic conventions. It represents the measure of - // memory used by buffers. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmBufferMemoryUsageName = "jvm.buffer.memory.usage" - JvmBufferMemoryUsageUnit = "By" - JvmBufferMemoryUsageDescription = "Measure of memory used by buffers." - - // JvmBufferMemoryLimit is the metric conforming to the - // "jvm.buffer.memory.limit" semantic conventions. It represents the measure of - // total memory capacity of buffers. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - JvmBufferMemoryLimitName = "jvm.buffer.memory.limit" - JvmBufferMemoryLimitUnit = "By" - JvmBufferMemoryLimitDescription = "Measure of total memory capacity of buffers." - - // JvmBufferCount is the metric conforming to the "jvm.buffer.count" semantic - // conventions. It represents the number of buffers in the pool. - // Instrument: updowncounter - // Unit: {buffer} - // Stability: Experimental - JvmBufferCountName = "jvm.buffer.count" - JvmBufferCountUnit = "{buffer}" - JvmBufferCountDescription = "Number of buffers in the pool." - - // JvmMemoryUsed is the metric conforming to the "jvm.memory.used" semantic - // conventions. It represents the measure of memory used. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryUsedName = "jvm.memory.used" - JvmMemoryUsedUnit = "By" - JvmMemoryUsedDescription = "Measure of memory used." - - // JvmMemoryCommitted is the metric conforming to the "jvm.memory.committed" - // semantic conventions. It represents the measure of memory committed. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryCommittedName = "jvm.memory.committed" - JvmMemoryCommittedUnit = "By" - JvmMemoryCommittedDescription = "Measure of memory committed." - - // JvmMemoryLimit is the metric conforming to the "jvm.memory.limit" semantic - // conventions. It represents the measure of max obtainable memory. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryLimitName = "jvm.memory.limit" - JvmMemoryLimitUnit = "By" - JvmMemoryLimitDescription = "Measure of max obtainable memory." - - // JvmMemoryUsedAfterLastGc is the metric conforming to the - // "jvm.memory.used_after_last_gc" semantic conventions. It represents the - // measure of memory used, as measured after the most recent garbage collection - // event on this pool. - // Instrument: updowncounter - // Unit: By - // Stability: Stable - JvmMemoryUsedAfterLastGcName = "jvm.memory.used_after_last_gc" - JvmMemoryUsedAfterLastGcUnit = "By" - JvmMemoryUsedAfterLastGcDescription = "Measure of memory used, as measured after the most recent garbage collection event on this pool." - - // JvmGcDuration is the metric conforming to the "jvm.gc.duration" semantic - // conventions. It represents the duration of JVM garbage collection actions. - // Instrument: histogram - // Unit: s - // Stability: Stable - JvmGcDurationName = "jvm.gc.duration" - JvmGcDurationUnit = "s" - JvmGcDurationDescription = "Duration of JVM garbage collection actions." - - // JvmThreadCount is the metric conforming to the "jvm.thread.count" semantic - // conventions. It represents the number of executing platform threads. - // Instrument: updowncounter - // Unit: {thread} - // Stability: Stable - JvmThreadCountName = "jvm.thread.count" - JvmThreadCountUnit = "{thread}" - JvmThreadCountDescription = "Number of executing platform threads." - - // JvmClassLoaded is the metric conforming to the "jvm.class.loaded" semantic - // conventions. It represents the number of classes loaded since JVM start. - // Instrument: counter - // Unit: {class} - // Stability: Stable - JvmClassLoadedName = "jvm.class.loaded" - JvmClassLoadedUnit = "{class}" - JvmClassLoadedDescription = "Number of classes loaded since JVM start." - - // JvmClassUnloaded is the metric conforming to the "jvm.class.unloaded" - // semantic conventions. It represents the number of classes unloaded since JVM - // start. - // Instrument: counter - // Unit: {class} - // Stability: Stable - JvmClassUnloadedName = "jvm.class.unloaded" - JvmClassUnloadedUnit = "{class}" - JvmClassUnloadedDescription = "Number of classes unloaded since JVM start." - - // JvmClassCount is the metric conforming to the "jvm.class.count" semantic - // conventions. It represents the number of classes currently loaded. - // Instrument: updowncounter - // Unit: {class} - // Stability: Stable - JvmClassCountName = "jvm.class.count" - JvmClassCountUnit = "{class}" - JvmClassCountDescription = "Number of classes currently loaded." - - // JvmCPUCount is the metric conforming to the "jvm.cpu.count" semantic - // conventions. It represents the number of processors available to the Java - // virtual machine. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Stable - JvmCPUCountName = "jvm.cpu.count" - JvmCPUCountUnit = "{cpu}" - JvmCPUCountDescription = "Number of processors available to the Java virtual machine." - - // JvmCPUTime is the metric conforming to the "jvm.cpu.time" semantic - // conventions. It represents the cPU time used by the process as reported by - // the JVM. - // Instrument: counter - // Unit: s - // Stability: Stable - JvmCPUTimeName = "jvm.cpu.time" - JvmCPUTimeUnit = "s" - JvmCPUTimeDescription = "CPU time used by the process as reported by the JVM." - - // JvmCPURecentUtilization is the metric conforming to the - // "jvm.cpu.recent_utilization" semantic conventions. It represents the recent - // CPU utilization for the process as reported by the JVM. - // Instrument: gauge - // Unit: 1 - // Stability: Stable - JvmCPURecentUtilizationName = "jvm.cpu.recent_utilization" - JvmCPURecentUtilizationUnit = "1" - JvmCPURecentUtilizationDescription = "Recent CPU utilization for the process as reported by the JVM." - - // MessagingPublishDuration is the metric conforming to the - // "messaging.publish.duration" semantic conventions. It represents the - // measures the duration of publish operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingPublishDurationName = "messaging.publish.duration" - MessagingPublishDurationUnit = "s" - MessagingPublishDurationDescription = "Measures the duration of publish operation." - - // MessagingReceiveDuration is the metric conforming to the - // "messaging.receive.duration" semantic conventions. It represents the - // measures the duration of receive operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingReceiveDurationName = "messaging.receive.duration" - MessagingReceiveDurationUnit = "s" - MessagingReceiveDurationDescription = "Measures the duration of receive operation." - - // MessagingDeliverDuration is the metric conforming to the - // "messaging.deliver.duration" semantic conventions. It represents the - // measures the duration of deliver operation. - // Instrument: histogram - // Unit: s - // Stability: Experimental - MessagingDeliverDurationName = "messaging.deliver.duration" - MessagingDeliverDurationUnit = "s" - MessagingDeliverDurationDescription = "Measures the duration of deliver operation." - - // MessagingPublishMessages is the metric conforming to the - // "messaging.publish.messages" semantic conventions. It represents the - // measures the number of published messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingPublishMessagesName = "messaging.publish.messages" - MessagingPublishMessagesUnit = "{message}" - MessagingPublishMessagesDescription = "Measures the number of published messages." - - // MessagingReceiveMessages is the metric conforming to the - // "messaging.receive.messages" semantic conventions. It represents the - // measures the number of received messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingReceiveMessagesName = "messaging.receive.messages" - MessagingReceiveMessagesUnit = "{message}" - MessagingReceiveMessagesDescription = "Measures the number of received messages." - - // MessagingDeliverMessages is the metric conforming to the - // "messaging.deliver.messages" semantic conventions. It represents the - // measures the number of delivered messages. - // Instrument: counter - // Unit: {message} - // Stability: Experimental - MessagingDeliverMessagesName = "messaging.deliver.messages" - MessagingDeliverMessagesUnit = "{message}" - MessagingDeliverMessagesDescription = "Measures the number of delivered messages." - - // RPCServerDuration is the metric conforming to the "rpc.server.duration" - // semantic conventions. It represents the measures the duration of inbound - // RPC. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - RPCServerDurationName = "rpc.server.duration" - RPCServerDurationUnit = "ms" - RPCServerDurationDescription = "Measures the duration of inbound RPC." - - // RPCServerRequestSize is the metric conforming to the - // "rpc.server.request.size" semantic conventions. It represents the measures - // the size of RPC request messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCServerRequestSizeName = "rpc.server.request.size" - RPCServerRequestSizeUnit = "By" - RPCServerRequestSizeDescription = "Measures the size of RPC request messages (uncompressed)." - - // RPCServerResponseSize is the metric conforming to the - // "rpc.server.response.size" semantic conventions. It represents the measures - // the size of RPC response messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCServerResponseSizeName = "rpc.server.response.size" - RPCServerResponseSizeUnit = "By" - RPCServerResponseSizeDescription = "Measures the size of RPC response messages (uncompressed)." - - // RPCServerRequestsPerRPC is the metric conforming to the - // "rpc.server.requests_per_rpc" semantic conventions. It represents the - // measures the number of messages received per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCServerRequestsPerRPCName = "rpc.server.requests_per_rpc" - RPCServerRequestsPerRPCUnit = "{count}" - RPCServerRequestsPerRPCDescription = "Measures the number of messages received per RPC." - - // RPCServerResponsesPerRPC is the metric conforming to the - // "rpc.server.responses_per_rpc" semantic conventions. It represents the - // measures the number of messages sent per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCServerResponsesPerRPCName = "rpc.server.responses_per_rpc" - RPCServerResponsesPerRPCUnit = "{count}" - RPCServerResponsesPerRPCDescription = "Measures the number of messages sent per RPC." - - // RPCClientDuration is the metric conforming to the "rpc.client.duration" - // semantic conventions. It represents the measures the duration of outbound - // RPC. - // Instrument: histogram - // Unit: ms - // Stability: Experimental - RPCClientDurationName = "rpc.client.duration" - RPCClientDurationUnit = "ms" - RPCClientDurationDescription = "Measures the duration of outbound RPC." - - // RPCClientRequestSize is the metric conforming to the - // "rpc.client.request.size" semantic conventions. It represents the measures - // the size of RPC request messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCClientRequestSizeName = "rpc.client.request.size" - RPCClientRequestSizeUnit = "By" - RPCClientRequestSizeDescription = "Measures the size of RPC request messages (uncompressed)." - - // RPCClientResponseSize is the metric conforming to the - // "rpc.client.response.size" semantic conventions. It represents the measures - // the size of RPC response messages (uncompressed). - // Instrument: histogram - // Unit: By - // Stability: Experimental - RPCClientResponseSizeName = "rpc.client.response.size" - RPCClientResponseSizeUnit = "By" - RPCClientResponseSizeDescription = "Measures the size of RPC response messages (uncompressed)." - - // RPCClientRequestsPerRPC is the metric conforming to the - // "rpc.client.requests_per_rpc" semantic conventions. It represents the - // measures the number of messages received per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCClientRequestsPerRPCName = "rpc.client.requests_per_rpc" - RPCClientRequestsPerRPCUnit = "{count}" - RPCClientRequestsPerRPCDescription = "Measures the number of messages received per RPC." - - // RPCClientResponsesPerRPC is the metric conforming to the - // "rpc.client.responses_per_rpc" semantic conventions. It represents the - // measures the number of messages sent per RPC. - // Instrument: histogram - // Unit: {count} - // Stability: Experimental - RPCClientResponsesPerRPCName = "rpc.client.responses_per_rpc" - RPCClientResponsesPerRPCUnit = "{count}" - RPCClientResponsesPerRPCDescription = "Measures the number of messages sent per RPC." - - // SystemCPUTime is the metric conforming to the "system.cpu.time" semantic - // conventions. It represents the seconds each logical CPU spent on each mode. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemCPUTimeName = "system.cpu.time" - SystemCPUTimeUnit = "s" - SystemCPUTimeDescription = "Seconds each logical CPU spent on each mode" - - // SystemCPUUtilization is the metric conforming to the - // "system.cpu.utilization" semantic conventions. It represents the difference - // in system.cpu.time since the last measurement, divided by the elapsed time - // and number of logical CPUs. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - SystemCPUUtilizationName = "system.cpu.utilization" - SystemCPUUtilizationUnit = "1" - SystemCPUUtilizationDescription = "Difference in system.cpu.time since the last measurement, divided by the elapsed time and number of logical CPUs" - - // SystemCPUFrequency is the metric conforming to the "system.cpu.frequency" - // semantic conventions. It represents the reports the current frequency of the - // CPU in Hz. - // Instrument: gauge - // Unit: {Hz} - // Stability: Experimental - SystemCPUFrequencyName = "system.cpu.frequency" - SystemCPUFrequencyUnit = "{Hz}" - SystemCPUFrequencyDescription = "Reports the current frequency of the CPU in Hz" - - // SystemCPUPhysicalCount is the metric conforming to the - // "system.cpu.physical.count" semantic conventions. It represents the reports - // the number of actual physical processor cores on the hardware. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Experimental - SystemCPUPhysicalCountName = "system.cpu.physical.count" - SystemCPUPhysicalCountUnit = "{cpu}" - SystemCPUPhysicalCountDescription = "Reports the number of actual physical processor cores on the hardware" - - // SystemCPULogicalCount is the metric conforming to the - // "system.cpu.logical.count" semantic conventions. It represents the reports - // the number of logical (virtual) processor cores created by the operating - // system to manage multitasking. - // Instrument: updowncounter - // Unit: {cpu} - // Stability: Experimental - SystemCPULogicalCountName = "system.cpu.logical.count" - SystemCPULogicalCountUnit = "{cpu}" - SystemCPULogicalCountDescription = "Reports the number of logical (virtual) processor cores created by the operating system to manage multitasking" - - // SystemMemoryUsage is the metric conforming to the "system.memory.usage" - // semantic conventions. It represents the reports memory in use by state. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemMemoryUsageName = "system.memory.usage" - SystemMemoryUsageUnit = "By" - SystemMemoryUsageDescription = "Reports memory in use by state." - - // SystemMemoryLimit is the metric conforming to the "system.memory.limit" - // semantic conventions. It represents the total memory available in the - // system. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemMemoryLimitName = "system.memory.limit" - SystemMemoryLimitUnit = "By" - SystemMemoryLimitDescription = "Total memory available in the system." - - // SystemMemoryUtilization is the metric conforming to the - // "system.memory.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemMemoryUtilizationName = "system.memory.utilization" - SystemMemoryUtilizationUnit = "1" - - // SystemPagingUsage is the metric conforming to the "system.paging.usage" - // semantic conventions. It represents the unix swap or windows pagefile usage. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemPagingUsageName = "system.paging.usage" - SystemPagingUsageUnit = "By" - SystemPagingUsageDescription = "Unix swap or windows pagefile usage" - - // SystemPagingUtilization is the metric conforming to the - // "system.paging.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingUtilizationName = "system.paging.utilization" - SystemPagingUtilizationUnit = "1" - - // SystemPagingFaults is the metric conforming to the "system.paging.faults" - // semantic conventions. - // Instrument: counter - // Unit: {fault} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingFaultsName = "system.paging.faults" - SystemPagingFaultsUnit = "{fault}" - - // SystemPagingOperations is the metric conforming to the - // "system.paging.operations" semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemPagingOperationsName = "system.paging.operations" - SystemPagingOperationsUnit = "{operation}" - - // SystemDiskIo is the metric conforming to the "system.disk.io" semantic - // conventions. - // Instrument: counter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskIoName = "system.disk.io" - SystemDiskIoUnit = "By" - - // SystemDiskOperations is the metric conforming to the - // "system.disk.operations" semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskOperationsName = "system.disk.operations" - SystemDiskOperationsUnit = "{operation}" - - // SystemDiskIoTime is the metric conforming to the "system.disk.io_time" - // semantic conventions. It represents the time disk spent activated. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemDiskIoTimeName = "system.disk.io_time" - SystemDiskIoTimeUnit = "s" - SystemDiskIoTimeDescription = "Time disk spent activated" - - // SystemDiskOperationTime is the metric conforming to the - // "system.disk.operation_time" semantic conventions. It represents the sum of - // the time each operation took to complete. - // Instrument: counter - // Unit: s - // Stability: Experimental - SystemDiskOperationTimeName = "system.disk.operation_time" - SystemDiskOperationTimeUnit = "s" - SystemDiskOperationTimeDescription = "Sum of the time each operation took to complete" - - // SystemDiskMerged is the metric conforming to the "system.disk.merged" - // semantic conventions. - // Instrument: counter - // Unit: {operation} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemDiskMergedName = "system.disk.merged" - SystemDiskMergedUnit = "{operation}" - - // SystemFilesystemUsage is the metric conforming to the - // "system.filesystem.usage" semantic conventions. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemFilesystemUsageName = "system.filesystem.usage" - SystemFilesystemUsageUnit = "By" - - // SystemFilesystemUtilization is the metric conforming to the - // "system.filesystem.utilization" semantic conventions. - // Instrument: gauge - // Unit: 1 - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemFilesystemUtilizationName = "system.filesystem.utilization" - SystemFilesystemUtilizationUnit = "1" - - // SystemNetworkDropped is the metric conforming to the - // "system.network.dropped" semantic conventions. It represents the count of - // packets that are dropped or discarded even though there was no error. - // Instrument: counter - // Unit: {packet} - // Stability: Experimental - SystemNetworkDroppedName = "system.network.dropped" - SystemNetworkDroppedUnit = "{packet}" - SystemNetworkDroppedDescription = "Count of packets that are dropped or discarded even though there was no error" - - // SystemNetworkPackets is the metric conforming to the - // "system.network.packets" semantic conventions. - // Instrument: counter - // Unit: {packet} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkPacketsName = "system.network.packets" - SystemNetworkPacketsUnit = "{packet}" - - // SystemNetworkErrors is the metric conforming to the "system.network.errors" - // semantic conventions. It represents the count of network errors detected. - // Instrument: counter - // Unit: {error} - // Stability: Experimental - SystemNetworkErrorsName = "system.network.errors" - SystemNetworkErrorsUnit = "{error}" - SystemNetworkErrorsDescription = "Count of network errors detected" - - // SystemNetworkIo is the metric conforming to the "system.network.io" semantic - // conventions. - // Instrument: counter - // Unit: By - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkIoName = "system.network.io" - SystemNetworkIoUnit = "By" - - // SystemNetworkConnections is the metric conforming to the - // "system.network.connections" semantic conventions. - // Instrument: updowncounter - // Unit: {connection} - // Stability: Experimental - // NOTE: The description (brief) for this metric is not defined in the semantic-conventions repository. - SystemNetworkConnectionsName = "system.network.connections" - SystemNetworkConnectionsUnit = "{connection}" - - // SystemProcessesCount is the metric conforming to the - // "system.processes.count" semantic conventions. It represents the total - // number of processes in each state. - // Instrument: updowncounter - // Unit: {process} - // Stability: Experimental - SystemProcessesCountName = "system.processes.count" - SystemProcessesCountUnit = "{process}" - SystemProcessesCountDescription = "Total number of processes in each state" - - // SystemProcessesCreated is the metric conforming to the - // "system.processes.created" semantic conventions. It represents the total - // number of processes created over uptime of the host. - // Instrument: counter - // Unit: {process} - // Stability: Experimental - SystemProcessesCreatedName = "system.processes.created" - SystemProcessesCreatedUnit = "{process}" - SystemProcessesCreatedDescription = "Total number of processes created over uptime of the host" - - // SystemLinuxMemoryAvailable is the metric conforming to the - // "system.linux.memory.available" semantic conventions. It represents an - // estimate of how much memory is available for starting new applications, - // without causing swapping. - // Instrument: updowncounter - // Unit: By - // Stability: Experimental - SystemLinuxMemoryAvailableName = "system.linux.memory.available" - SystemLinuxMemoryAvailableUnit = "By" - SystemLinuxMemoryAvailableDescription = "An estimate of how much memory is available for starting new applications, without causing swapping" -) diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go deleted file mode 100644 index d66bbe9c2..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go +++ /dev/null @@ -1,2545 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -import "go.opentelemetry.io/otel/attribute" - -// A cloud environment (e.g. GCP, Azure, AWS). -const ( - // CloudAccountIDKey is the attribute Key conforming to the - // "cloud.account.id" semantic conventions. It represents the cloud account - // ID the resource is assigned to. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '111111111111', 'opentelemetry' - CloudAccountIDKey = attribute.Key("cloud.account.id") - - // CloudAvailabilityZoneKey is the attribute Key conforming to the - // "cloud.availability_zone" semantic conventions. It represents the cloud - // regions often have multiple, isolated locations known as zones to - // increase availability. Availability zone represents the zone where the - // resource is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-east-1c' - // Note: Availability zones are called "zones" on Alibaba Cloud and Google - // Cloud. - CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") - - // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" - // semantic conventions. It represents the cloud platform in use. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The prefix of the service SHOULD match the one specified in - // `cloud.provider`. - CloudPlatformKey = attribute.Key("cloud.platform") - - // CloudProviderKey is the attribute Key conforming to the "cloud.provider" - // semantic conventions. It represents the name of the cloud provider. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - CloudProviderKey = attribute.Key("cloud.provider") - - // CloudRegionKey is the attribute Key conforming to the "cloud.region" - // semantic conventions. It represents the geographical region the resource - // is running. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'us-central1', 'us-east-1' - // Note: Refer to your provider's docs to see the available regions, for - // example [Alibaba Cloud - // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS - // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), - // [Azure - // regions](https://azure.microsoft.com/global-infrastructure/geographies/), - // [Google Cloud regions](https://cloud.google.com/about/locations), or - // [Tencent Cloud - // regions](https://www.tencentcloud.com/document/product/213/6091). - CloudRegionKey = attribute.Key("cloud.region") - - // CloudResourceIDKey is the attribute Key conforming to the - // "cloud.resource_id" semantic conventions. It represents the cloud - // provider-specific native identifier of the monitored cloud resource - // (e.g. an - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // on AWS, a [fully qualified resource - // ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) - // on Azure, a [full resource - // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // on GCP) - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:lambda:REGION:ACCOUNT_ID:function:my-function', - // '//run.googleapis.com/projects/PROJECT_ID/locations/LOCATION_ID/services/SERVICE_ID', - // '/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/' - // Note: On some cloud providers, it may not be possible to determine the - // full ID at startup, - // so it may be necessary to set `cloud.resource_id` as a span attribute - // instead. - // - // The exact value to use for `cloud.resource_id` depends on the cloud - // provider. - // The following well-known definitions MUST be used if you set this - // attribute and they apply: - // - // * **AWS Lambda:** The function - // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - // Take care not to use the "invoked ARN" directly but replace any - // [alias - // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) - // with the resolved function version, as the same runtime instance may - // be invokable with - // multiple different aliases. - // * **GCP:** The [URI of the - // resource](https://cloud.google.com/iam/docs/full-resource-names) - // * **Azure:** The [Fully Qualified Resource - // ID](https://docs.microsoft.com/rest/api/resources/resources/get-by-id) - // of the invoked function, - // *not* the function app, having the form - // `/subscriptions//resourceGroups//providers/Microsoft.Web/sites//functions/`. - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider. - CloudResourceIDKey = attribute.Key("cloud.resource_id") -) - -var ( - // Alibaba Cloud Elastic Compute Service - CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") - // Alibaba Cloud Function Compute - CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") - // Red Hat OpenShift on Alibaba Cloud - CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") - // AWS Elastic Compute Cloud - CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") - // AWS Elastic Container Service - CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") - // AWS Elastic Kubernetes Service - CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") - // AWS Lambda - CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") - // AWS Elastic Beanstalk - CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") - // AWS App Runner - CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") - // Red Hat OpenShift on AWS (ROSA) - CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") - // Azure Virtual Machines - CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") - // Azure Container Instances - CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") - // Azure Kubernetes Service - CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") - // Azure Functions - CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") - // Azure App Service - CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") - // Azure Red Hat OpenShift - CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") - // Google Bare Metal Solution (BMS) - CloudPlatformGCPBareMetalSolution = CloudPlatformKey.String("gcp_bare_metal_solution") - // Google Cloud Compute Engine (GCE) - CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") - // Google Cloud Run - CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") - // Google Cloud Kubernetes Engine (GKE) - CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") - // Google Cloud Functions (GCF) - CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") - // Google Cloud App Engine (GAE) - CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") - // Red Hat OpenShift on Google Cloud - CloudPlatformGCPOpenshift = CloudPlatformKey.String("gcp_openshift") - // Red Hat OpenShift on IBM Cloud - CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") - // Tencent Cloud Cloud Virtual Machine (CVM) - CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") - // Tencent Cloud Elastic Kubernetes Service (EKS) - CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") - // Tencent Cloud Serverless Cloud Function (SCF) - CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") -) - -var ( - // Alibaba Cloud - CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") - // Amazon Web Services - CloudProviderAWS = CloudProviderKey.String("aws") - // Microsoft Azure - CloudProviderAzure = CloudProviderKey.String("azure") - // Google Cloud Platform - CloudProviderGCP = CloudProviderKey.String("gcp") - // Heroku Platform as a Service - CloudProviderHeroku = CloudProviderKey.String("heroku") - // IBM Cloud - CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") - // Tencent Cloud - CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") -) - -// CloudAccountID returns an attribute KeyValue conforming to the -// "cloud.account.id" semantic conventions. It represents the cloud account ID -// the resource is assigned to. -func CloudAccountID(val string) attribute.KeyValue { - return CloudAccountIDKey.String(val) -} - -// CloudAvailabilityZone returns an attribute KeyValue conforming to the -// "cloud.availability_zone" semantic conventions. It represents the cloud -// regions often have multiple, isolated locations known as zones to increase -// availability. Availability zone represents the zone where the resource is -// running. -func CloudAvailabilityZone(val string) attribute.KeyValue { - return CloudAvailabilityZoneKey.String(val) -} - -// CloudRegion returns an attribute KeyValue conforming to the -// "cloud.region" semantic conventions. It represents the geographical region -// the resource is running. -func CloudRegion(val string) attribute.KeyValue { - return CloudRegionKey.String(val) -} - -// CloudResourceID returns an attribute KeyValue conforming to the -// "cloud.resource_id" semantic conventions. It represents the cloud -// provider-specific native identifier of the monitored cloud resource (e.g. an -// [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) -// on AWS, a [fully qualified resource -// ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) on -// Azure, a [full resource -// name](https://cloud.google.com/apis/design/resource_names#full_resource_name) -// on GCP) -func CloudResourceID(val string) attribute.KeyValue { - return CloudResourceIDKey.String(val) -} - -// A container instance. -const ( - // ContainerCommandKey is the attribute Key conforming to the - // "container.command" semantic conventions. It represents the command used - // to run the container (i.e. the command name). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol' - // Note: If using embedded credentials or sensitive data, it is recommended - // to remove them to prevent potential leakage. - ContainerCommandKey = attribute.Key("container.command") - - // ContainerCommandArgsKey is the attribute Key conforming to the - // "container.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) run by the - // container. [2] - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol, --config, config.yaml' - ContainerCommandArgsKey = attribute.Key("container.command_args") - - // ContainerCommandLineKey is the attribute Key conforming to the - // "container.command_line" semantic conventions. It represents the full - // command run by the container as a single string representing the full - // command. [2] - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcontribcol --config config.yaml' - ContainerCommandLineKey = attribute.Key("container.command_line") - - // ContainerIDKey is the attribute Key conforming to the "container.id" - // semantic conventions. It represents the container ID. Usually a UUID, as - // for example used to [identify Docker - // containers](https://docs.docker.com/engine/reference/run/#container-identification). - // The UUID might be abbreviated. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'a3bf90e006b2' - ContainerIDKey = attribute.Key("container.id") - - // ContainerImageIDKey is the attribute Key conforming to the - // "container.image.id" semantic conventions. It represents the runtime - // specific image identifier. Usually a hash algorithm followed by a UUID. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'sha256:19c92d0a00d1b66d897bceaa7319bee0dd38a10a851c60bcec9474aa3f01e50f' - // Note: Docker defines a sha256 of the image id; `container.image.id` - // corresponds to the `Image` field from the Docker container inspect - // [API](https://docs.docker.com/engine/api/v1.43/#tag/Container/operation/ContainerInspect) - // endpoint. - // K8S defines a link to the container registry repository with digest - // `"imageID": "registry.azurecr.io - // /namespace/service/dockerfile@sha256:bdeabd40c3a8a492eaf9e8e44d0ebbb84bac7ee25ac0cf8a7159d25f62555625"`. - // The ID is assinged by the container runtime and can vary in different - // environments. Consider using `oci.manifest.digest` if it is important to - // identify the same image in different environments/runtimes. - ContainerImageIDKey = attribute.Key("container.image.id") - - // ContainerImageNameKey is the attribute Key conforming to the - // "container.image.name" semantic conventions. It represents the name of - // the image the container was built on. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'gcr.io/opentelemetry/operator' - ContainerImageNameKey = attribute.Key("container.image.name") - - // ContainerImageRepoDigestsKey is the attribute Key conforming to the - // "container.image.repo_digests" semantic conventions. It represents the - // repo digests of the container image as provided by the container - // runtime. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb', - // 'internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578' - // Note: - // [Docker](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect) - // and - // [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) - // report those under the `RepoDigests` field. - ContainerImageRepoDigestsKey = attribute.Key("container.image.repo_digests") - - // ContainerImageTagsKey is the attribute Key conforming to the - // "container.image.tags" semantic conventions. It represents the container - // image tags. An example can be found in [Docker Image - // Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). - // Should be only the `` section of the full name for example from - // `registry.example.com/my-org/my-image:`. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'v1.27.1', '3.5.7-0' - ContainerImageTagsKey = attribute.Key("container.image.tags") - - // ContainerNameKey is the attribute Key conforming to the "container.name" - // semantic conventions. It represents the container name used by container - // runtime. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-autoconf' - ContainerNameKey = attribute.Key("container.name") - - // ContainerRuntimeKey is the attribute Key conforming to the - // "container.runtime" semantic conventions. It represents the container - // runtime managing this container. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'docker', 'containerd', 'rkt' - ContainerRuntimeKey = attribute.Key("container.runtime") -) - -// ContainerCommand returns an attribute KeyValue conforming to the -// "container.command" semantic conventions. It represents the command used to -// run the container (i.e. the command name). -func ContainerCommand(val string) attribute.KeyValue { - return ContainerCommandKey.String(val) -} - -// ContainerCommandArgs returns an attribute KeyValue conforming to the -// "container.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) run by the -// container. [2] -func ContainerCommandArgs(val ...string) attribute.KeyValue { - return ContainerCommandArgsKey.StringSlice(val) -} - -// ContainerCommandLine returns an attribute KeyValue conforming to the -// "container.command_line" semantic conventions. It represents the full -// command run by the container as a single string representing the full -// command. [2] -func ContainerCommandLine(val string) attribute.KeyValue { - return ContainerCommandLineKey.String(val) -} - -// ContainerID returns an attribute KeyValue conforming to the -// "container.id" semantic conventions. It represents the container ID. Usually -// a UUID, as for example used to [identify Docker -// containers](https://docs.docker.com/engine/reference/run/#container-identification). -// The UUID might be abbreviated. -func ContainerID(val string) attribute.KeyValue { - return ContainerIDKey.String(val) -} - -// ContainerImageID returns an attribute KeyValue conforming to the -// "container.image.id" semantic conventions. It represents the runtime -// specific image identifier. Usually a hash algorithm followed by a UUID. -func ContainerImageID(val string) attribute.KeyValue { - return ContainerImageIDKey.String(val) -} - -// ContainerImageName returns an attribute KeyValue conforming to the -// "container.image.name" semantic conventions. It represents the name of the -// image the container was built on. -func ContainerImageName(val string) attribute.KeyValue { - return ContainerImageNameKey.String(val) -} - -// ContainerImageRepoDigests returns an attribute KeyValue conforming to the -// "container.image.repo_digests" semantic conventions. It represents the repo -// digests of the container image as provided by the container runtime. -func ContainerImageRepoDigests(val ...string) attribute.KeyValue { - return ContainerImageRepoDigestsKey.StringSlice(val) -} - -// ContainerImageTags returns an attribute KeyValue conforming to the -// "container.image.tags" semantic conventions. It represents the container -// image tags. An example can be found in [Docker Image -// Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). -// Should be only the `` section of the full name for example from -// `registry.example.com/my-org/my-image:`. -func ContainerImageTags(val ...string) attribute.KeyValue { - return ContainerImageTagsKey.StringSlice(val) -} - -// ContainerName returns an attribute KeyValue conforming to the -// "container.name" semantic conventions. It represents the container name used -// by container runtime. -func ContainerName(val string) attribute.KeyValue { - return ContainerNameKey.String(val) -} - -// ContainerRuntime returns an attribute KeyValue conforming to the -// "container.runtime" semantic conventions. It represents the container -// runtime managing this container. -func ContainerRuntime(val string) attribute.KeyValue { - return ContainerRuntimeKey.String(val) -} - -// Describes device attributes. -const ( - // DeviceIDKey is the attribute Key conforming to the "device.id" semantic - // conventions. It represents a unique identifier representing the device - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' - // Note: The device identifier MUST only be defined using the values - // outlined below. This value is not an advertising identifier and MUST NOT - // be used as such. On iOS (Swift or Objective-C), this value MUST be equal - // to the [vendor - // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). - // On Android (Java or Kotlin), this value MUST be equal to the Firebase - // Installation ID or a globally unique UUID which is persisted across - // sessions in your application. More information can be found - // [here](https://developer.android.com/training/articles/user-data-ids) on - // best practices and exact implementation details. Caution should be taken - // when storing personal data or anything which can identify a user. GDPR - // and data protection laws may apply, ensure you do your own due - // diligence. - DeviceIDKey = attribute.Key("device.id") - - // DeviceManufacturerKey is the attribute Key conforming to the - // "device.manufacturer" semantic conventions. It represents the name of - // the device manufacturer - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Apple', 'Samsung' - // Note: The Android OS provides this field via - // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). - // iOS apps SHOULD hardcode the value `Apple`. - DeviceManufacturerKey = attribute.Key("device.manufacturer") - - // DeviceModelIdentifierKey is the attribute Key conforming to the - // "device.model.identifier" semantic conventions. It represents the model - // identifier for the device - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iPhone3,4', 'SM-G920F' - // Note: It's recommended this value represents a machine-readable version - // of the model identifier rather than the market or consumer-friendly name - // of the device. - DeviceModelIdentifierKey = attribute.Key("device.model.identifier") - - // DeviceModelNameKey is the attribute Key conforming to the - // "device.model.name" semantic conventions. It represents the marketing - // name for the device model - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' - // Note: It's recommended this value represents a human-readable version of - // the device model rather than a machine-readable alternative. - DeviceModelNameKey = attribute.Key("device.model.name") -) - -// DeviceID returns an attribute KeyValue conforming to the "device.id" -// semantic conventions. It represents a unique identifier representing the -// device -func DeviceID(val string) attribute.KeyValue { - return DeviceIDKey.String(val) -} - -// DeviceManufacturer returns an attribute KeyValue conforming to the -// "device.manufacturer" semantic conventions. It represents the name of the -// device manufacturer -func DeviceManufacturer(val string) attribute.KeyValue { - return DeviceManufacturerKey.String(val) -} - -// DeviceModelIdentifier returns an attribute KeyValue conforming to the -// "device.model.identifier" semantic conventions. It represents the model -// identifier for the device -func DeviceModelIdentifier(val string) attribute.KeyValue { - return DeviceModelIdentifierKey.String(val) -} - -// DeviceModelName returns an attribute KeyValue conforming to the -// "device.model.name" semantic conventions. It represents the marketing name -// for the device model -func DeviceModelName(val string) attribute.KeyValue { - return DeviceModelNameKey.String(val) -} - -// A host is defined as a computing instance. For example, physical servers, -// virtual machines, switches or disk array. -const ( - // HostArchKey is the attribute Key conforming to the "host.arch" semantic - // conventions. It represents the CPU architecture the host system is - // running on. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - HostArchKey = attribute.Key("host.arch") - - // HostCPUCacheL2SizeKey is the attribute Key conforming to the - // "host.cpu.cache.l2.size" semantic conventions. It represents the amount - // of level 2 memory cache available to the processor (in Bytes). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 12288000 - HostCPUCacheL2SizeKey = attribute.Key("host.cpu.cache.l2.size") - - // HostCPUFamilyKey is the attribute Key conforming to the - // "host.cpu.family" semantic conventions. It represents the family or - // generation of the CPU. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '6', 'PA-RISC 1.1e' - HostCPUFamilyKey = attribute.Key("host.cpu.family") - - // HostCPUModelIDKey is the attribute Key conforming to the - // "host.cpu.model.id" semantic conventions. It represents the model - // identifier. It provides more granular information about the CPU, - // distinguishing it from other CPUs within the same family. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '6', '9000/778/B180L' - HostCPUModelIDKey = attribute.Key("host.cpu.model.id") - - // HostCPUModelNameKey is the attribute Key conforming to the - // "host.cpu.model.name" semantic conventions. It represents the model - // designation of the processor. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz' - HostCPUModelNameKey = attribute.Key("host.cpu.model.name") - - // HostCPUSteppingKey is the attribute Key conforming to the - // "host.cpu.stepping" semantic conventions. It represents the stepping or - // core revisions. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1 - HostCPUSteppingKey = attribute.Key("host.cpu.stepping") - - // HostCPUVendorIDKey is the attribute Key conforming to the - // "host.cpu.vendor.id" semantic conventions. It represents the processor - // manufacturer identifier. A maximum 12-character string. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'GenuineIntel' - // Note: [CPUID](https://wiki.osdev.org/CPUID) command returns the vendor - // ID string in EBX, EDX and ECX registers. Writing these to memory in this - // order results in a 12-character string. - HostCPUVendorIDKey = attribute.Key("host.cpu.vendor.id") - - // HostIDKey is the attribute Key conforming to the "host.id" semantic - // conventions. It represents the unique host ID. For Cloud, this must be - // the instance_id assigned by the cloud provider. For non-containerized - // systems, this should be the `machine-id`. See the table below for the - // sources to use to determine the `machine-id` based on operating system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'fdbf79e8af94cb7f9e8df36789187052' - HostIDKey = attribute.Key("host.id") - - // HostImageIDKey is the attribute Key conforming to the "host.image.id" - // semantic conventions. It represents the vM image ID or host OS image ID. - // For Cloud, this value is from the provider. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ami-07b06b442921831e5' - HostImageIDKey = attribute.Key("host.image.id") - - // HostImageNameKey is the attribute Key conforming to the - // "host.image.name" semantic conventions. It represents the name of the VM - // image or OS install the host was instantiated from. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'infra-ami-eks-worker-node-7d4ec78312', 'CentOS-8-x86_64-1905' - HostImageNameKey = attribute.Key("host.image.name") - - // HostImageVersionKey is the attribute Key conforming to the - // "host.image.version" semantic conventions. It represents the version - // string of the VM image or host OS as defined in [Version - // Attributes](/docs/resource/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0.1' - HostImageVersionKey = attribute.Key("host.image.version") - - // HostIPKey is the attribute Key conforming to the "host.ip" semantic - // conventions. It represents the available IP addresses of the host, - // excluding loopback interfaces. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '192.168.1.140', 'fe80::abc2:4a28:737a:609e' - // Note: IPv4 Addresses MUST be specified in dotted-quad notation. IPv6 - // addresses MUST be specified in the [RFC - // 5952](https://www.rfc-editor.org/rfc/rfc5952.html) format. - HostIPKey = attribute.Key("host.ip") - - // HostMacKey is the attribute Key conforming to the "host.mac" semantic - // conventions. It represents the available MAC addresses of the host, - // excluding loopback interfaces. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'AC-DE-48-23-45-67', 'AC-DE-48-23-45-67-01-9F' - // Note: MAC Addresses MUST be represented in [IEEE RA hexadecimal - // form](https://standards.ieee.org/wp-content/uploads/import/documents/tutorials/eui.pdf): - // as hyphen-separated octets in uppercase hexadecimal form from most to - // least significant. - HostMacKey = attribute.Key("host.mac") - - // HostNameKey is the attribute Key conforming to the "host.name" semantic - // conventions. It represents the name of the host. On Unix systems, it may - // contain what the hostname command returns, or the fully qualified - // hostname, or another name specified by the user. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-test' - HostNameKey = attribute.Key("host.name") - - // HostTypeKey is the attribute Key conforming to the "host.type" semantic - // conventions. It represents the type of host. For Cloud, this must be the - // machine type. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'n1-standard-1' - HostTypeKey = attribute.Key("host.type") -) - -var ( - // AMD64 - HostArchAMD64 = HostArchKey.String("amd64") - // ARM32 - HostArchARM32 = HostArchKey.String("arm32") - // ARM64 - HostArchARM64 = HostArchKey.String("arm64") - // Itanium - HostArchIA64 = HostArchKey.String("ia64") - // 32-bit PowerPC - HostArchPPC32 = HostArchKey.String("ppc32") - // 64-bit PowerPC - HostArchPPC64 = HostArchKey.String("ppc64") - // IBM z/Architecture - HostArchS390x = HostArchKey.String("s390x") - // 32-bit x86 - HostArchX86 = HostArchKey.String("x86") -) - -// HostCPUCacheL2Size returns an attribute KeyValue conforming to the -// "host.cpu.cache.l2.size" semantic conventions. It represents the amount of -// level 2 memory cache available to the processor (in Bytes). -func HostCPUCacheL2Size(val int) attribute.KeyValue { - return HostCPUCacheL2SizeKey.Int(val) -} - -// HostCPUFamily returns an attribute KeyValue conforming to the -// "host.cpu.family" semantic conventions. It represents the family or -// generation of the CPU. -func HostCPUFamily(val string) attribute.KeyValue { - return HostCPUFamilyKey.String(val) -} - -// HostCPUModelID returns an attribute KeyValue conforming to the -// "host.cpu.model.id" semantic conventions. It represents the model -// identifier. It provides more granular information about the CPU, -// distinguishing it from other CPUs within the same family. -func HostCPUModelID(val string) attribute.KeyValue { - return HostCPUModelIDKey.String(val) -} - -// HostCPUModelName returns an attribute KeyValue conforming to the -// "host.cpu.model.name" semantic conventions. It represents the model -// designation of the processor. -func HostCPUModelName(val string) attribute.KeyValue { - return HostCPUModelNameKey.String(val) -} - -// HostCPUStepping returns an attribute KeyValue conforming to the -// "host.cpu.stepping" semantic conventions. It represents the stepping or core -// revisions. -func HostCPUStepping(val int) attribute.KeyValue { - return HostCPUSteppingKey.Int(val) -} - -// HostCPUVendorID returns an attribute KeyValue conforming to the -// "host.cpu.vendor.id" semantic conventions. It represents the processor -// manufacturer identifier. A maximum 12-character string. -func HostCPUVendorID(val string) attribute.KeyValue { - return HostCPUVendorIDKey.String(val) -} - -// HostID returns an attribute KeyValue conforming to the "host.id" semantic -// conventions. It represents the unique host ID. For Cloud, this must be the -// instance_id assigned by the cloud provider. For non-containerized systems, -// this should be the `machine-id`. See the table below for the sources to use -// to determine the `machine-id` based on operating system. -func HostID(val string) attribute.KeyValue { - return HostIDKey.String(val) -} - -// HostImageID returns an attribute KeyValue conforming to the -// "host.image.id" semantic conventions. It represents the vM image ID or host -// OS image ID. For Cloud, this value is from the provider. -func HostImageID(val string) attribute.KeyValue { - return HostImageIDKey.String(val) -} - -// HostImageName returns an attribute KeyValue conforming to the -// "host.image.name" semantic conventions. It represents the name of the VM -// image or OS install the host was instantiated from. -func HostImageName(val string) attribute.KeyValue { - return HostImageNameKey.String(val) -} - -// HostImageVersion returns an attribute KeyValue conforming to the -// "host.image.version" semantic conventions. It represents the version string -// of the VM image or host OS as defined in [Version -// Attributes](/docs/resource/README.md#version-attributes). -func HostImageVersion(val string) attribute.KeyValue { - return HostImageVersionKey.String(val) -} - -// HostIP returns an attribute KeyValue conforming to the "host.ip" semantic -// conventions. It represents the available IP addresses of the host, excluding -// loopback interfaces. -func HostIP(val ...string) attribute.KeyValue { - return HostIPKey.StringSlice(val) -} - -// HostMac returns an attribute KeyValue conforming to the "host.mac" -// semantic conventions. It represents the available MAC addresses of the host, -// excluding loopback interfaces. -func HostMac(val ...string) attribute.KeyValue { - return HostMacKey.StringSlice(val) -} - -// HostName returns an attribute KeyValue conforming to the "host.name" -// semantic conventions. It represents the name of the host. On Unix systems, -// it may contain what the hostname command returns, or the fully qualified -// hostname, or another name specified by the user. -func HostName(val string) attribute.KeyValue { - return HostNameKey.String(val) -} - -// HostType returns an attribute KeyValue conforming to the "host.type" -// semantic conventions. It represents the type of host. For Cloud, this must -// be the machine type. -func HostType(val string) attribute.KeyValue { - return HostTypeKey.String(val) -} - -// Kubernetes resource attributes. -const ( - // K8SClusterNameKey is the attribute Key conforming to the - // "k8s.cluster.name" semantic conventions. It represents the name of the - // cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-cluster' - K8SClusterNameKey = attribute.Key("k8s.cluster.name") - - // K8SClusterUIDKey is the attribute Key conforming to the - // "k8s.cluster.uid" semantic conventions. It represents a pseudo-ID for - // the cluster, set to the UID of the `kube-system` namespace. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '218fc5a9-a5f1-4b54-aa05-46717d0ab26d' - // Note: K8S doesn't have support for obtaining a cluster ID. If this is - // ever - // added, we will recommend collecting the `k8s.cluster.uid` through the - // official APIs. In the meantime, we are able to use the `uid` of the - // `kube-system` namespace as a proxy for cluster ID. Read on for the - // rationale. - // - // Every object created in a K8S cluster is assigned a distinct UID. The - // `kube-system` namespace is used by Kubernetes itself and will exist - // for the lifetime of the cluster. Using the `uid` of the `kube-system` - // namespace is a reasonable proxy for the K8S ClusterID as it will only - // change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are - // UUIDs as standardized by - // [ISO/IEC 9834-8 and ITU-T - // X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html). - // Which states: - // - // > If generated according to one of the mechanisms defined in Rec. - // ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be - // different from all other UUIDs generated before 3603 A.D., or is - // extremely likely to be different (depending on the mechanism chosen). - // - // Therefore, UIDs between clusters should be extremely unlikely to - // conflict. - K8SClusterUIDKey = attribute.Key("k8s.cluster.uid") - - // K8SContainerNameKey is the attribute Key conforming to the - // "k8s.container.name" semantic conventions. It represents the name of the - // Container from Pod specification, must be unique within a Pod. Container - // runtime usually uses different globally unique name (`container.name`). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'redis' - K8SContainerNameKey = attribute.Key("k8s.container.name") - - // K8SContainerRestartCountKey is the attribute Key conforming to the - // "k8s.container.restart_count" semantic conventions. It represents the - // number of times the container was restarted. This attribute can be used - // to identify a particular container (running or stopped) within a - // container spec. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 2 - K8SContainerRestartCountKey = attribute.Key("k8s.container.restart_count") - - // K8SCronJobNameKey is the attribute Key conforming to the - // "k8s.cronjob.name" semantic conventions. It represents the name of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SCronJobNameKey = attribute.Key("k8s.cronjob.name") - - // K8SCronJobUIDKey is the attribute Key conforming to the - // "k8s.cronjob.uid" semantic conventions. It represents the UID of the - // CronJob. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SCronJobUIDKey = attribute.Key("k8s.cronjob.uid") - - // K8SDaemonSetNameKey is the attribute Key conforming to the - // "k8s.daemonset.name" semantic conventions. It represents the name of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SDaemonSetNameKey = attribute.Key("k8s.daemonset.name") - - // K8SDaemonSetUIDKey is the attribute Key conforming to the - // "k8s.daemonset.uid" semantic conventions. It represents the UID of the - // DaemonSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDaemonSetUIDKey = attribute.Key("k8s.daemonset.uid") - - // K8SDeploymentNameKey is the attribute Key conforming to the - // "k8s.deployment.name" semantic conventions. It represents the name of - // the Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SDeploymentNameKey = attribute.Key("k8s.deployment.name") - - // K8SDeploymentUIDKey is the attribute Key conforming to the - // "k8s.deployment.uid" semantic conventions. It represents the UID of the - // Deployment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SDeploymentUIDKey = attribute.Key("k8s.deployment.uid") - - // K8SJobNameKey is the attribute Key conforming to the "k8s.job.name" - // semantic conventions. It represents the name of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SJobNameKey = attribute.Key("k8s.job.name") - - // K8SJobUIDKey is the attribute Key conforming to the "k8s.job.uid" - // semantic conventions. It represents the UID of the Job. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SJobUIDKey = attribute.Key("k8s.job.uid") - - // K8SNamespaceNameKey is the attribute Key conforming to the - // "k8s.namespace.name" semantic conventions. It represents the name of the - // namespace that the pod is running in. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'default' - K8SNamespaceNameKey = attribute.Key("k8s.namespace.name") - - // K8SNodeNameKey is the attribute Key conforming to the "k8s.node.name" - // semantic conventions. It represents the name of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'node-1' - K8SNodeNameKey = attribute.Key("k8s.node.name") - - // K8SNodeUIDKey is the attribute Key conforming to the "k8s.node.uid" - // semantic conventions. It represents the UID of the Node. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2' - K8SNodeUIDKey = attribute.Key("k8s.node.uid") - - // K8SPodNameKey is the attribute Key conforming to the "k8s.pod.name" - // semantic conventions. It represents the name of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-pod-autoconf' - K8SPodNameKey = attribute.Key("k8s.pod.name") - - // K8SPodUIDKey is the attribute Key conforming to the "k8s.pod.uid" - // semantic conventions. It represents the UID of the Pod. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SPodUIDKey = attribute.Key("k8s.pod.uid") - - // K8SReplicaSetNameKey is the attribute Key conforming to the - // "k8s.replicaset.name" semantic conventions. It represents the name of - // the ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SReplicaSetNameKey = attribute.Key("k8s.replicaset.name") - - // K8SReplicaSetUIDKey is the attribute Key conforming to the - // "k8s.replicaset.uid" semantic conventions. It represents the UID of the - // ReplicaSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SReplicaSetUIDKey = attribute.Key("k8s.replicaset.uid") - - // K8SStatefulSetNameKey is the attribute Key conforming to the - // "k8s.statefulset.name" semantic conventions. It represents the name of - // the StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry' - K8SStatefulSetNameKey = attribute.Key("k8s.statefulset.name") - - // K8SStatefulSetUIDKey is the attribute Key conforming to the - // "k8s.statefulset.uid" semantic conventions. It represents the UID of the - // StatefulSet. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '275ecb36-5aa8-4c2a-9c47-d8bb681b9aff' - K8SStatefulSetUIDKey = attribute.Key("k8s.statefulset.uid") -) - -// K8SClusterName returns an attribute KeyValue conforming to the -// "k8s.cluster.name" semantic conventions. It represents the name of the -// cluster. -func K8SClusterName(val string) attribute.KeyValue { - return K8SClusterNameKey.String(val) -} - -// K8SClusterUID returns an attribute KeyValue conforming to the -// "k8s.cluster.uid" semantic conventions. It represents a pseudo-ID for the -// cluster, set to the UID of the `kube-system` namespace. -func K8SClusterUID(val string) attribute.KeyValue { - return K8SClusterUIDKey.String(val) -} - -// K8SContainerName returns an attribute KeyValue conforming to the -// "k8s.container.name" semantic conventions. It represents the name of the -// Container from Pod specification, must be unique within a Pod. Container -// runtime usually uses different globally unique name (`container.name`). -func K8SContainerName(val string) attribute.KeyValue { - return K8SContainerNameKey.String(val) -} - -// K8SContainerRestartCount returns an attribute KeyValue conforming to the -// "k8s.container.restart_count" semantic conventions. It represents the number -// of times the container was restarted. This attribute can be used to identify -// a particular container (running or stopped) within a container spec. -func K8SContainerRestartCount(val int) attribute.KeyValue { - return K8SContainerRestartCountKey.Int(val) -} - -// K8SCronJobName returns an attribute KeyValue conforming to the -// "k8s.cronjob.name" semantic conventions. It represents the name of the -// CronJob. -func K8SCronJobName(val string) attribute.KeyValue { - return K8SCronJobNameKey.String(val) -} - -// K8SCronJobUID returns an attribute KeyValue conforming to the -// "k8s.cronjob.uid" semantic conventions. It represents the UID of the -// CronJob. -func K8SCronJobUID(val string) attribute.KeyValue { - return K8SCronJobUIDKey.String(val) -} - -// K8SDaemonSetName returns an attribute KeyValue conforming to the -// "k8s.daemonset.name" semantic conventions. It represents the name of the -// DaemonSet. -func K8SDaemonSetName(val string) attribute.KeyValue { - return K8SDaemonSetNameKey.String(val) -} - -// K8SDaemonSetUID returns an attribute KeyValue conforming to the -// "k8s.daemonset.uid" semantic conventions. It represents the UID of the -// DaemonSet. -func K8SDaemonSetUID(val string) attribute.KeyValue { - return K8SDaemonSetUIDKey.String(val) -} - -// K8SDeploymentName returns an attribute KeyValue conforming to the -// "k8s.deployment.name" semantic conventions. It represents the name of the -// Deployment. -func K8SDeploymentName(val string) attribute.KeyValue { - return K8SDeploymentNameKey.String(val) -} - -// K8SDeploymentUID returns an attribute KeyValue conforming to the -// "k8s.deployment.uid" semantic conventions. It represents the UID of the -// Deployment. -func K8SDeploymentUID(val string) attribute.KeyValue { - return K8SDeploymentUIDKey.String(val) -} - -// K8SJobName returns an attribute KeyValue conforming to the "k8s.job.name" -// semantic conventions. It represents the name of the Job. -func K8SJobName(val string) attribute.KeyValue { - return K8SJobNameKey.String(val) -} - -// K8SJobUID returns an attribute KeyValue conforming to the "k8s.job.uid" -// semantic conventions. It represents the UID of the Job. -func K8SJobUID(val string) attribute.KeyValue { - return K8SJobUIDKey.String(val) -} - -// K8SNamespaceName returns an attribute KeyValue conforming to the -// "k8s.namespace.name" semantic conventions. It represents the name of the -// namespace that the pod is running in. -func K8SNamespaceName(val string) attribute.KeyValue { - return K8SNamespaceNameKey.String(val) -} - -// K8SNodeName returns an attribute KeyValue conforming to the -// "k8s.node.name" semantic conventions. It represents the name of the Node. -func K8SNodeName(val string) attribute.KeyValue { - return K8SNodeNameKey.String(val) -} - -// K8SNodeUID returns an attribute KeyValue conforming to the "k8s.node.uid" -// semantic conventions. It represents the UID of the Node. -func K8SNodeUID(val string) attribute.KeyValue { - return K8SNodeUIDKey.String(val) -} - -// K8SPodName returns an attribute KeyValue conforming to the "k8s.pod.name" -// semantic conventions. It represents the name of the Pod. -func K8SPodName(val string) attribute.KeyValue { - return K8SPodNameKey.String(val) -} - -// K8SPodUID returns an attribute KeyValue conforming to the "k8s.pod.uid" -// semantic conventions. It represents the UID of the Pod. -func K8SPodUID(val string) attribute.KeyValue { - return K8SPodUIDKey.String(val) -} - -// K8SReplicaSetName returns an attribute KeyValue conforming to the -// "k8s.replicaset.name" semantic conventions. It represents the name of the -// ReplicaSet. -func K8SReplicaSetName(val string) attribute.KeyValue { - return K8SReplicaSetNameKey.String(val) -} - -// K8SReplicaSetUID returns an attribute KeyValue conforming to the -// "k8s.replicaset.uid" semantic conventions. It represents the UID of the -// ReplicaSet. -func K8SReplicaSetUID(val string) attribute.KeyValue { - return K8SReplicaSetUIDKey.String(val) -} - -// K8SStatefulSetName returns an attribute KeyValue conforming to the -// "k8s.statefulset.name" semantic conventions. It represents the name of the -// StatefulSet. -func K8SStatefulSetName(val string) attribute.KeyValue { - return K8SStatefulSetNameKey.String(val) -} - -// K8SStatefulSetUID returns an attribute KeyValue conforming to the -// "k8s.statefulset.uid" semantic conventions. It represents the UID of the -// StatefulSet. -func K8SStatefulSetUID(val string) attribute.KeyValue { - return K8SStatefulSetUIDKey.String(val) -} - -// An OCI image manifest. -const ( - // OciManifestDigestKey is the attribute Key conforming to the - // "oci.manifest.digest" semantic conventions. It represents the digest of - // the OCI image manifest. For container images specifically is the digest - // by which the container image is known. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'sha256:e4ca62c0d62f3e886e684806dfe9d4e0cda60d54986898173c1083856cfda0f4' - // Note: Follows [OCI Image Manifest - // Specification](https://github.com/opencontainers/image-spec/blob/main/manifest.md), - // and specifically the [Digest - // property](https://github.com/opencontainers/image-spec/blob/main/descriptor.md#digests). - // An example can be found in [Example Image - // Manifest](https://docs.docker.com/registry/spec/manifest-v2-2/#example-image-manifest). - OciManifestDigestKey = attribute.Key("oci.manifest.digest") -) - -// OciManifestDigest returns an attribute KeyValue conforming to the -// "oci.manifest.digest" semantic conventions. It represents the digest of the -// OCI image manifest. For container images specifically is the digest by which -// the container image is known. -func OciManifestDigest(val string) attribute.KeyValue { - return OciManifestDigestKey.String(val) -} - -// The operating system (OS) on which the process represented by this resource -// is running. -const ( - // OSBuildIDKey is the attribute Key conforming to the "os.build_id" - // semantic conventions. It represents the unique identifier for a - // particular build or compilation of the operating system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'TQ3C.230805.001.B2', '20E247', '22621' - OSBuildIDKey = attribute.Key("os.build_id") - - // OSDescriptionKey is the attribute Key conforming to the "os.description" - // semantic conventions. It represents the human readable (not intended to - // be parsed) OS version information, like e.g. reported by `ver` or - // `lsb_release -a` commands. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Microsoft Windows [Version 10.0.18363.778]', 'Ubuntu 18.04.1 - // LTS' - OSDescriptionKey = attribute.Key("os.description") - - // OSNameKey is the attribute Key conforming to the "os.name" semantic - // conventions. It represents the human readable operating system name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'iOS', 'Android', 'Ubuntu' - OSNameKey = attribute.Key("os.name") - - // OSTypeKey is the attribute Key conforming to the "os.type" semantic - // conventions. It represents the operating system type. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - OSTypeKey = attribute.Key("os.type") - - // OSVersionKey is the attribute Key conforming to the "os.version" - // semantic conventions. It represents the version string of the operating - // system as defined in [Version - // Attributes](/docs/resource/README.md#version-attributes). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '14.2.1', '18.04.1' - OSVersionKey = attribute.Key("os.version") -) - -var ( - // Microsoft Windows - OSTypeWindows = OSTypeKey.String("windows") - // Linux - OSTypeLinux = OSTypeKey.String("linux") - // Apple Darwin - OSTypeDarwin = OSTypeKey.String("darwin") - // FreeBSD - OSTypeFreeBSD = OSTypeKey.String("freebsd") - // NetBSD - OSTypeNetBSD = OSTypeKey.String("netbsd") - // OpenBSD - OSTypeOpenBSD = OSTypeKey.String("openbsd") - // DragonFly BSD - OSTypeDragonflyBSD = OSTypeKey.String("dragonflybsd") - // HP-UX (Hewlett Packard Unix) - OSTypeHPUX = OSTypeKey.String("hpux") - // AIX (Advanced Interactive eXecutive) - OSTypeAIX = OSTypeKey.String("aix") - // SunOS, Oracle Solaris - OSTypeSolaris = OSTypeKey.String("solaris") - // IBM z/OS - OSTypeZOS = OSTypeKey.String("z_os") -) - -// OSBuildID returns an attribute KeyValue conforming to the "os.build_id" -// semantic conventions. It represents the unique identifier for a particular -// build or compilation of the operating system. -func OSBuildID(val string) attribute.KeyValue { - return OSBuildIDKey.String(val) -} - -// OSDescription returns an attribute KeyValue conforming to the -// "os.description" semantic conventions. It represents the human readable (not -// intended to be parsed) OS version information, like e.g. reported by `ver` -// or `lsb_release -a` commands. -func OSDescription(val string) attribute.KeyValue { - return OSDescriptionKey.String(val) -} - -// OSName returns an attribute KeyValue conforming to the "os.name" semantic -// conventions. It represents the human readable operating system name. -func OSName(val string) attribute.KeyValue { - return OSNameKey.String(val) -} - -// OSVersion returns an attribute KeyValue conforming to the "os.version" -// semantic conventions. It represents the version string of the operating -// system as defined in [Version -// Attributes](/docs/resource/README.md#version-attributes). -func OSVersion(val string) attribute.KeyValue { - return OSVersionKey.String(val) -} - -// An operating system process. -const ( - // ProcessCommandKey is the attribute Key conforming to the - // "process.command" semantic conventions. It represents the command used - // to launch the process (i.e. the command name). On Linux based systems, - // can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can - // be set to the first parameter extracted from `GetCommandLineW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'cmd/otelcol' - ProcessCommandKey = attribute.Key("process.command") - - // ProcessCommandArgsKey is the attribute Key conforming to the - // "process.command_args" semantic conventions. It represents the all the - // command arguments (including the command/executable itself) as received - // by the process. On Linux-based systems (and some other Unixoid systems - // supporting procfs), can be set according to the list of null-delimited - // strings extracted from `proc/[pid]/cmdline`. For libc-based executables, - // this would be the full argv vector passed to `main`. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'cmd/otecol', '--config=config.yaml' - ProcessCommandArgsKey = attribute.Key("process.command_args") - - // ProcessCommandLineKey is the attribute Key conforming to the - // "process.command_line" semantic conventions. It represents the full - // command used to launch the process as a single string representing the - // full command. On Windows, can be set to the result of `GetCommandLineW`. - // Do not set this if you have to assemble it just for monitoring; use - // `process.command_args` instead. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'C:\\cmd\\otecol --config="my directory\\config.yaml"' - ProcessCommandLineKey = attribute.Key("process.command_line") - - // ProcessExecutableNameKey is the attribute Key conforming to the - // "process.executable.name" semantic conventions. It represents the name - // of the process executable. On Linux based systems, can be set to the - // `Name` in `proc/[pid]/status`. On Windows, can be set to the base name - // of `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'otelcol' - ProcessExecutableNameKey = attribute.Key("process.executable.name") - - // ProcessExecutablePathKey is the attribute Key conforming to the - // "process.executable.path" semantic conventions. It represents the full - // path to the process executable. On Linux based systems, can be set to - // the target of `proc/[pid]/exe`. On Windows, can be set to the result of - // `GetProcessImageFileNameW`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/usr/bin/cmd/otelcol' - ProcessExecutablePathKey = attribute.Key("process.executable.path") - - // ProcessOwnerKey is the attribute Key conforming to the "process.owner" - // semantic conventions. It represents the username of the user that owns - // the process. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'root' - ProcessOwnerKey = attribute.Key("process.owner") - - // ProcessParentPIDKey is the attribute Key conforming to the - // "process.parent_pid" semantic conventions. It represents the parent - // Process identifier (PPID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 111 - ProcessParentPIDKey = attribute.Key("process.parent_pid") - - // ProcessPIDKey is the attribute Key conforming to the "process.pid" - // semantic conventions. It represents the process identifier (PID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1234 - ProcessPIDKey = attribute.Key("process.pid") - - // ProcessRuntimeDescriptionKey is the attribute Key conforming to the - // "process.runtime.description" semantic conventions. It represents an - // additional description about the runtime of the process, for example a - // specific vendor customization of the runtime environment. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0' - ProcessRuntimeDescriptionKey = attribute.Key("process.runtime.description") - - // ProcessRuntimeNameKey is the attribute Key conforming to the - // "process.runtime.name" semantic conventions. It represents the name of - // the runtime of this process. For compiled native binaries, this SHOULD - // be the name of the compiler. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'OpenJDK Runtime Environment' - ProcessRuntimeNameKey = attribute.Key("process.runtime.name") - - // ProcessRuntimeVersionKey is the attribute Key conforming to the - // "process.runtime.version" semantic conventions. It represents the - // version of the runtime of this process, as returned by the runtime - // without modification. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '14.0.2' - ProcessRuntimeVersionKey = attribute.Key("process.runtime.version") -) - -// ProcessCommand returns an attribute KeyValue conforming to the -// "process.command" semantic conventions. It represents the command used to -// launch the process (i.e. the command name). On Linux based systems, can be -// set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to -// the first parameter extracted from `GetCommandLineW`. -func ProcessCommand(val string) attribute.KeyValue { - return ProcessCommandKey.String(val) -} - -// ProcessCommandArgs returns an attribute KeyValue conforming to the -// "process.command_args" semantic conventions. It represents the all the -// command arguments (including the command/executable itself) as received by -// the process. On Linux-based systems (and some other Unixoid systems -// supporting procfs), can be set according to the list of null-delimited -// strings extracted from `proc/[pid]/cmdline`. For libc-based executables, -// this would be the full argv vector passed to `main`. -func ProcessCommandArgs(val ...string) attribute.KeyValue { - return ProcessCommandArgsKey.StringSlice(val) -} - -// ProcessCommandLine returns an attribute KeyValue conforming to the -// "process.command_line" semantic conventions. It represents the full command -// used to launch the process as a single string representing the full command. -// On Windows, can be set to the result of `GetCommandLineW`. Do not set this -// if you have to assemble it just for monitoring; use `process.command_args` -// instead. -func ProcessCommandLine(val string) attribute.KeyValue { - return ProcessCommandLineKey.String(val) -} - -// ProcessExecutableName returns an attribute KeyValue conforming to the -// "process.executable.name" semantic conventions. It represents the name of -// the process executable. On Linux based systems, can be set to the `Name` in -// `proc/[pid]/status`. On Windows, can be set to the base name of -// `GetProcessImageFileNameW`. -func ProcessExecutableName(val string) attribute.KeyValue { - return ProcessExecutableNameKey.String(val) -} - -// ProcessExecutablePath returns an attribute KeyValue conforming to the -// "process.executable.path" semantic conventions. It represents the full path -// to the process executable. On Linux based systems, can be set to the target -// of `proc/[pid]/exe`. On Windows, can be set to the result of -// `GetProcessImageFileNameW`. -func ProcessExecutablePath(val string) attribute.KeyValue { - return ProcessExecutablePathKey.String(val) -} - -// ProcessOwner returns an attribute KeyValue conforming to the -// "process.owner" semantic conventions. It represents the username of the user -// that owns the process. -func ProcessOwner(val string) attribute.KeyValue { - return ProcessOwnerKey.String(val) -} - -// ProcessParentPID returns an attribute KeyValue conforming to the -// "process.parent_pid" semantic conventions. It represents the parent Process -// identifier (PPID). -func ProcessParentPID(val int) attribute.KeyValue { - return ProcessParentPIDKey.Int(val) -} - -// ProcessPID returns an attribute KeyValue conforming to the "process.pid" -// semantic conventions. It represents the process identifier (PID). -func ProcessPID(val int) attribute.KeyValue { - return ProcessPIDKey.Int(val) -} - -// ProcessRuntimeDescription returns an attribute KeyValue conforming to the -// "process.runtime.description" semantic conventions. It represents an -// additional description about the runtime of the process, for example a -// specific vendor customization of the runtime environment. -func ProcessRuntimeDescription(val string) attribute.KeyValue { - return ProcessRuntimeDescriptionKey.String(val) -} - -// ProcessRuntimeName returns an attribute KeyValue conforming to the -// "process.runtime.name" semantic conventions. It represents the name of the -// runtime of this process. For compiled native binaries, this SHOULD be the -// name of the compiler. -func ProcessRuntimeName(val string) attribute.KeyValue { - return ProcessRuntimeNameKey.String(val) -} - -// ProcessRuntimeVersion returns an attribute KeyValue conforming to the -// "process.runtime.version" semantic conventions. It represents the version of -// the runtime of this process, as returned by the runtime without -// modification. -func ProcessRuntimeVersion(val string) attribute.KeyValue { - return ProcessRuntimeVersionKey.String(val) -} - -// The Android platform on which the Android application is running. -const ( - // AndroidOSAPILevelKey is the attribute Key conforming to the - // "android.os.api_level" semantic conventions. It represents the uniquely - // identifies the framework API revision offered by a version - // (`os.version`) of the android operating system. More information can be - // found - // [here](https://developer.android.com/guide/topics/manifest/uses-sdk-element#APILevels). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '33', '32' - AndroidOSAPILevelKey = attribute.Key("android.os.api_level") -) - -// AndroidOSAPILevel returns an attribute KeyValue conforming to the -// "android.os.api_level" semantic conventions. It represents the uniquely -// identifies the framework API revision offered by a version (`os.version`) of -// the android operating system. More information can be found -// [here](https://developer.android.com/guide/topics/manifest/uses-sdk-element#APILevels). -func AndroidOSAPILevel(val string) attribute.KeyValue { - return AndroidOSAPILevelKey.String(val) -} - -// The web browser in which the application represented by the resource is -// running. The `browser.*` attributes MUST be used only for resources that -// represent applications running in a web browser (regardless of whether -// running on a mobile or desktop device). -const ( - // BrowserBrandsKey is the attribute Key conforming to the "browser.brands" - // semantic conventions. It represents the array of brand name and version - // separated by a space - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: ' Not A;Brand 99', 'Chromium 99', 'Chrome 99' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.brands`). - BrowserBrandsKey = attribute.Key("browser.brands") - - // BrowserLanguageKey is the attribute Key conforming to the - // "browser.language" semantic conventions. It represents the preferred - // language of the user using the browser - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'en', 'en-US', 'fr', 'fr-FR' - // Note: This value is intended to be taken from the Navigator API - // `navigator.language`. - BrowserLanguageKey = attribute.Key("browser.language") - - // BrowserMobileKey is the attribute Key conforming to the "browser.mobile" - // semantic conventions. It represents a boolean that is true if the - // browser is running on a mobile device - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.mobile`). If unavailable, this attribute - // SHOULD be left unset. - BrowserMobileKey = attribute.Key("browser.mobile") - - // BrowserPlatformKey is the attribute Key conforming to the - // "browser.platform" semantic conventions. It represents the platform on - // which the browser is running - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Windows', 'macOS', 'Android' - // Note: This value is intended to be taken from the [UA client hints - // API](https://wicg.github.io/ua-client-hints/#interface) - // (`navigator.userAgentData.platform`). If unavailable, the legacy - // `navigator.platform` API SHOULD NOT be used instead and this attribute - // SHOULD be left unset in order for the values to be consistent. - // The list of possible values is defined in the [W3C User-Agent Client - // Hints - // specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). - // Note that some (but not all) of these values can overlap with values in - // the [`os.type` and `os.name` attributes](./os.md). However, for - // consistency, the values in the `browser.platform` attribute should - // capture the exact value that the user agent provides. - BrowserPlatformKey = attribute.Key("browser.platform") -) - -// BrowserBrands returns an attribute KeyValue conforming to the -// "browser.brands" semantic conventions. It represents the array of brand name -// and version separated by a space -func BrowserBrands(val ...string) attribute.KeyValue { - return BrowserBrandsKey.StringSlice(val) -} - -// BrowserLanguage returns an attribute KeyValue conforming to the -// "browser.language" semantic conventions. It represents the preferred -// language of the user using the browser -func BrowserLanguage(val string) attribute.KeyValue { - return BrowserLanguageKey.String(val) -} - -// BrowserMobile returns an attribute KeyValue conforming to the -// "browser.mobile" semantic conventions. It represents a boolean that is true -// if the browser is running on a mobile device -func BrowserMobile(val bool) attribute.KeyValue { - return BrowserMobileKey.Bool(val) -} - -// BrowserPlatform returns an attribute KeyValue conforming to the -// "browser.platform" semantic conventions. It represents the platform on which -// the browser is running -func BrowserPlatform(val string) attribute.KeyValue { - return BrowserPlatformKey.String(val) -} - -// Resources used by AWS Elastic Container Service (ECS). -const ( - // AWSECSClusterARNKey is the attribute Key conforming to the - // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an - // [ECS - // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSECSClusterARNKey = attribute.Key("aws.ecs.cluster.arn") - - // AWSECSContainerARNKey is the attribute Key conforming to the - // "aws.ecs.container.arn" semantic conventions. It represents the Amazon - // Resource Name (ARN) of an [ECS container - // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:container/32624152-9086-4f0e-acae-1a75b14fe4d9' - AWSECSContainerARNKey = attribute.Key("aws.ecs.container.arn") - - // AWSECSLaunchtypeKey is the attribute Key conforming to the - // "aws.ecs.launchtype" semantic conventions. It represents the [launch - // type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) - // for an ECS task. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - AWSECSLaunchtypeKey = attribute.Key("aws.ecs.launchtype") - - // AWSECSTaskARNKey is the attribute Key conforming to the - // "aws.ecs.task.arn" semantic conventions. It represents the ARN of an - // [ECS task - // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:ecs:us-west-1:123456789123:task/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSECSTaskARNKey = attribute.Key("aws.ecs.task.arn") - - // AWSECSTaskFamilyKey is the attribute Key conforming to the - // "aws.ecs.task.family" semantic conventions. It represents the task - // definition family this task definition is a member of. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'opentelemetry-family' - AWSECSTaskFamilyKey = attribute.Key("aws.ecs.task.family") - - // AWSECSTaskRevisionKey is the attribute Key conforming to the - // "aws.ecs.task.revision" semantic conventions. It represents the revision - // for this task definition. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '8', '26' - AWSECSTaskRevisionKey = attribute.Key("aws.ecs.task.revision") -) - -var ( - // ec2 - AWSECSLaunchtypeEC2 = AWSECSLaunchtypeKey.String("ec2") - // fargate - AWSECSLaunchtypeFargate = AWSECSLaunchtypeKey.String("fargate") -) - -// AWSECSClusterARN returns an attribute KeyValue conforming to the -// "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an [ECS -// cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). -func AWSECSClusterARN(val string) attribute.KeyValue { - return AWSECSClusterARNKey.String(val) -} - -// AWSECSContainerARN returns an attribute KeyValue conforming to the -// "aws.ecs.container.arn" semantic conventions. It represents the Amazon -// Resource Name (ARN) of an [ECS container -// instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). -func AWSECSContainerARN(val string) attribute.KeyValue { - return AWSECSContainerARNKey.String(val) -} - -// AWSECSTaskARN returns an attribute KeyValue conforming to the -// "aws.ecs.task.arn" semantic conventions. It represents the ARN of an [ECS -// task -// definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). -func AWSECSTaskARN(val string) attribute.KeyValue { - return AWSECSTaskARNKey.String(val) -} - -// AWSECSTaskFamily returns an attribute KeyValue conforming to the -// "aws.ecs.task.family" semantic conventions. It represents the task -// definition family this task definition is a member of. -func AWSECSTaskFamily(val string) attribute.KeyValue { - return AWSECSTaskFamilyKey.String(val) -} - -// AWSECSTaskRevision returns an attribute KeyValue conforming to the -// "aws.ecs.task.revision" semantic conventions. It represents the revision for -// this task definition. -func AWSECSTaskRevision(val string) attribute.KeyValue { - return AWSECSTaskRevisionKey.String(val) -} - -// Resources used by AWS Elastic Kubernetes Service (EKS). -const ( - // AWSEKSClusterARNKey is the attribute Key conforming to the - // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an - // EKS cluster. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' - AWSEKSClusterARNKey = attribute.Key("aws.eks.cluster.arn") -) - -// AWSEKSClusterARN returns an attribute KeyValue conforming to the -// "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an EKS -// cluster. -func AWSEKSClusterARN(val string) attribute.KeyValue { - return AWSEKSClusterARNKey.String(val) -} - -// Resources specific to Amazon Web Services. -const ( - // AWSLogGroupARNsKey is the attribute Key conforming to the - // "aws.log.group.arns" semantic conventions. It represents the Amazon - // Resource Name(s) (ARN) of the AWS log group(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:*' - // Note: See the [log group ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - AWSLogGroupARNsKey = attribute.Key("aws.log.group.arns") - - // AWSLogGroupNamesKey is the attribute Key conforming to the - // "aws.log.group.names" semantic conventions. It represents the name(s) of - // the AWS log group(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/aws/lambda/my-function', 'opentelemetry-service' - // Note: Multiple log groups must be supported for cases like - // multi-container applications, where a single application has sidecar - // containers, and each write to their own log group. - AWSLogGroupNamesKey = attribute.Key("aws.log.group.names") - - // AWSLogStreamARNsKey is the attribute Key conforming to the - // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of - // the AWS log stream(s). - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:log-stream:logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - // Note: See the [log stream ARN format - // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - // One log group can contain several log streams, so these ARNs necessarily - // identify both a log group and a log stream. - AWSLogStreamARNsKey = attribute.Key("aws.log.stream.arns") - - // AWSLogStreamNamesKey is the attribute Key conforming to the - // "aws.log.stream.names" semantic conventions. It represents the name(s) - // of the AWS log stream(s) an application is writing to. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' - AWSLogStreamNamesKey = attribute.Key("aws.log.stream.names") -) - -// AWSLogGroupARNs returns an attribute KeyValue conforming to the -// "aws.log.group.arns" semantic conventions. It represents the Amazon Resource -// Name(s) (ARN) of the AWS log group(s). -func AWSLogGroupARNs(val ...string) attribute.KeyValue { - return AWSLogGroupARNsKey.StringSlice(val) -} - -// AWSLogGroupNames returns an attribute KeyValue conforming to the -// "aws.log.group.names" semantic conventions. It represents the name(s) of the -// AWS log group(s) an application is writing to. -func AWSLogGroupNames(val ...string) attribute.KeyValue { - return AWSLogGroupNamesKey.StringSlice(val) -} - -// AWSLogStreamARNs returns an attribute KeyValue conforming to the -// "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of the -// AWS log stream(s). -func AWSLogStreamARNs(val ...string) attribute.KeyValue { - return AWSLogStreamARNsKey.StringSlice(val) -} - -// AWSLogStreamNames returns an attribute KeyValue conforming to the -// "aws.log.stream.names" semantic conventions. It represents the name(s) of -// the AWS log stream(s) an application is writing to. -func AWSLogStreamNames(val ...string) attribute.KeyValue { - return AWSLogStreamNamesKey.StringSlice(val) -} - -// Resource used by Google Cloud Run. -const ( - // GCPCloudRunJobExecutionKey is the attribute Key conforming to the - // "gcp.cloud_run.job.execution" semantic conventions. It represents the - // name of the Cloud Run - // [execution](https://cloud.google.com/run/docs/managing/job-executions) - // being run for the Job, as set by the - // [`CLOUD_RUN_EXECUTION`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) - // environment variable. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'job-name-xxxx', 'sample-job-mdw84' - GCPCloudRunJobExecutionKey = attribute.Key("gcp.cloud_run.job.execution") - - // GCPCloudRunJobTaskIndexKey is the attribute Key conforming to the - // "gcp.cloud_run.job.task_index" semantic conventions. It represents the - // index for a task within an execution as provided by the - // [`CLOUD_RUN_TASK_INDEX`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) - // environment variable. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 0, 1 - GCPCloudRunJobTaskIndexKey = attribute.Key("gcp.cloud_run.job.task_index") -) - -// GCPCloudRunJobExecution returns an attribute KeyValue conforming to the -// "gcp.cloud_run.job.execution" semantic conventions. It represents the name -// of the Cloud Run -// [execution](https://cloud.google.com/run/docs/managing/job-executions) being -// run for the Job, as set by the -// [`CLOUD_RUN_EXECUTION`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) -// environment variable. -func GCPCloudRunJobExecution(val string) attribute.KeyValue { - return GCPCloudRunJobExecutionKey.String(val) -} - -// GCPCloudRunJobTaskIndex returns an attribute KeyValue conforming to the -// "gcp.cloud_run.job.task_index" semantic conventions. It represents the index -// for a task within an execution as provided by the -// [`CLOUD_RUN_TASK_INDEX`](https://cloud.google.com/run/docs/container-contract#jobs-env-vars) -// environment variable. -func GCPCloudRunJobTaskIndex(val int) attribute.KeyValue { - return GCPCloudRunJobTaskIndexKey.Int(val) -} - -// Resources used by Google Compute Engine (GCE). -const ( - // GCPGceInstanceHostnameKey is the attribute Key conforming to the - // "gcp.gce.instance.hostname" semantic conventions. It represents the - // hostname of a GCE instance. This is the full value of the default or - // [custom - // hostname](https://cloud.google.com/compute/docs/instances/custom-hostname-vm). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-host1234.example.com', - // 'sample-vm.us-west1-b.c.my-project.internal' - GCPGceInstanceHostnameKey = attribute.Key("gcp.gce.instance.hostname") - - // GCPGceInstanceNameKey is the attribute Key conforming to the - // "gcp.gce.instance.name" semantic conventions. It represents the instance - // name of a GCE instance. This is the value provided by `host.name`, the - // visible name of the instance in the Cloud Console UI, and the prefix for - // the default hostname of the instance as defined by the [default internal - // DNS - // name](https://cloud.google.com/compute/docs/internal-dns#instance-fully-qualified-domain-names). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'instance-1', 'my-vm-name' - GCPGceInstanceNameKey = attribute.Key("gcp.gce.instance.name") -) - -// GCPGceInstanceHostname returns an attribute KeyValue conforming to the -// "gcp.gce.instance.hostname" semantic conventions. It represents the hostname -// of a GCE instance. This is the full value of the default or [custom -// hostname](https://cloud.google.com/compute/docs/instances/custom-hostname-vm). -func GCPGceInstanceHostname(val string) attribute.KeyValue { - return GCPGceInstanceHostnameKey.String(val) -} - -// GCPGceInstanceName returns an attribute KeyValue conforming to the -// "gcp.gce.instance.name" semantic conventions. It represents the instance -// name of a GCE instance. This is the value provided by `host.name`, the -// visible name of the instance in the Cloud Console UI, and the prefix for the -// default hostname of the instance as defined by the [default internal DNS -// name](https://cloud.google.com/compute/docs/internal-dns#instance-fully-qualified-domain-names). -func GCPGceInstanceName(val string) attribute.KeyValue { - return GCPGceInstanceNameKey.String(val) -} - -// Heroku dyno metadata -const ( - // HerokuAppIDKey is the attribute Key conforming to the "heroku.app.id" - // semantic conventions. It represents the unique identifier for the - // application - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2daa2797-e42b-4624-9322-ec3f968df4da' - HerokuAppIDKey = attribute.Key("heroku.app.id") - - // HerokuReleaseCommitKey is the attribute Key conforming to the - // "heroku.release.commit" semantic conventions. It represents the commit - // hash for the current release - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'e6134959463efd8966b20e75b913cafe3f5ec' - HerokuReleaseCommitKey = attribute.Key("heroku.release.commit") - - // HerokuReleaseCreationTimestampKey is the attribute Key conforming to the - // "heroku.release.creation_timestamp" semantic conventions. It represents - // the time and date the release was created - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2022-10-23T18:00:42Z' - HerokuReleaseCreationTimestampKey = attribute.Key("heroku.release.creation_timestamp") -) - -// HerokuAppID returns an attribute KeyValue conforming to the -// "heroku.app.id" semantic conventions. It represents the unique identifier -// for the application -func HerokuAppID(val string) attribute.KeyValue { - return HerokuAppIDKey.String(val) -} - -// HerokuReleaseCommit returns an attribute KeyValue conforming to the -// "heroku.release.commit" semantic conventions. It represents the commit hash -// for the current release -func HerokuReleaseCommit(val string) attribute.KeyValue { - return HerokuReleaseCommitKey.String(val) -} - -// HerokuReleaseCreationTimestamp returns an attribute KeyValue conforming -// to the "heroku.release.creation_timestamp" semantic conventions. It -// represents the time and date the release was created -func HerokuReleaseCreationTimestamp(val string) attribute.KeyValue { - return HerokuReleaseCreationTimestampKey.String(val) -} - -// The software deployment. -const ( - // DeploymentEnvironmentKey is the attribute Key conforming to the - // "deployment.environment" semantic conventions. It represents the name of - // the [deployment - // environment](https://wikipedia.org/wiki/Deployment_environment) (aka - // deployment tier). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'staging', 'production' - // Note: `deployment.environment` does not affect the uniqueness - // constraints defined through - // the `service.namespace`, `service.name` and `service.instance.id` - // resource attributes. - // This implies that resources carrying the following attribute - // combinations MUST be - // considered to be identifying the same service: - // - // * `service.name=frontend`, `deployment.environment=production` - // * `service.name=frontend`, `deployment.environment=staging`. - DeploymentEnvironmentKey = attribute.Key("deployment.environment") -) - -// DeploymentEnvironment returns an attribute KeyValue conforming to the -// "deployment.environment" semantic conventions. It represents the name of the -// [deployment environment](https://wikipedia.org/wiki/Deployment_environment) -// (aka deployment tier). -func DeploymentEnvironment(val string) attribute.KeyValue { - return DeploymentEnvironmentKey.String(val) -} - -// A serverless instance. -const ( - // FaaSInstanceKey is the attribute Key conforming to the "faas.instance" - // semantic conventions. It represents the execution environment ID as a - // string, that will be potentially reused for other invocations to the - // same function/function version. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2021/06/28/[$LATEST]2f399eb14537447da05ab2a2e39309de' - // Note: * **AWS Lambda:** Use the (full) log stream name. - FaaSInstanceKey = attribute.Key("faas.instance") - - // FaaSMaxMemoryKey is the attribute Key conforming to the - // "faas.max_memory" semantic conventions. It represents the amount of - // memory available to the serverless function converted to Bytes. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 134217728 - // Note: It's recommended to set this attribute since e.g. too little - // memory can easily stop a Java AWS Lambda function from working - // correctly. On AWS Lambda, the environment variable - // `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information (which must - // be multiplied by 1,048,576). - FaaSMaxMemoryKey = attribute.Key("faas.max_memory") - - // FaaSNameKey is the attribute Key conforming to the "faas.name" semantic - // conventions. It represents the name of the single function that this - // runtime instance executes. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'my-function', 'myazurefunctionapp/some-function-name' - // Note: This is the name of the function as configured/deployed on the - // FaaS - // platform and is usually different from the name of the callback - // function (which may be stored in the - // [`code.namespace`/`code.function`](/docs/general/attributes.md#source-code-attributes) - // span attributes). - // - // For some cloud providers, the above definition is ambiguous. The - // following - // definition of function name MUST be used for this attribute - // (and consequently the span name) for the listed cloud - // providers/products: - // - // * **Azure:** The full name `/`, i.e., function app name - // followed by a forward slash followed by the function name (this form - // can also be seen in the resource JSON for the function). - // This means that a span attribute MUST be used, as an Azure function - // app can host multiple functions that would usually share - // a TracerProvider (see also the `cloud.resource_id` attribute). - FaaSNameKey = attribute.Key("faas.name") - - // FaaSVersionKey is the attribute Key conforming to the "faas.version" - // semantic conventions. It represents the immutable version of the - // function being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '26', 'pinkfroid-00002' - // Note: Depending on the cloud provider and platform, use: - // - // * **AWS Lambda:** The [function - // version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - // (an integer represented as a decimal string). - // * **Google Cloud Run (Services):** The - // [revision](https://cloud.google.com/run/docs/managing/revisions) - // (i.e., the function name plus the revision suffix). - // * **Google Cloud Functions:** The value of the - // [`K_REVISION` environment - // variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - // * **Azure Functions:** Not applicable. Do not set this attribute. - FaaSVersionKey = attribute.Key("faas.version") -) - -// FaaSInstance returns an attribute KeyValue conforming to the -// "faas.instance" semantic conventions. It represents the execution -// environment ID as a string, that will be potentially reused for other -// invocations to the same function/function version. -func FaaSInstance(val string) attribute.KeyValue { - return FaaSInstanceKey.String(val) -} - -// FaaSMaxMemory returns an attribute KeyValue conforming to the -// "faas.max_memory" semantic conventions. It represents the amount of memory -// available to the serverless function converted to Bytes. -func FaaSMaxMemory(val int) attribute.KeyValue { - return FaaSMaxMemoryKey.Int(val) -} - -// FaaSName returns an attribute KeyValue conforming to the "faas.name" -// semantic conventions. It represents the name of the single function that -// this runtime instance executes. -func FaaSName(val string) attribute.KeyValue { - return FaaSNameKey.String(val) -} - -// FaaSVersion returns an attribute KeyValue conforming to the -// "faas.version" semantic conventions. It represents the immutable version of -// the function being executed. -func FaaSVersion(val string) attribute.KeyValue { - return FaaSVersionKey.String(val) -} - -// A service instance. -const ( - // ServiceNameKey is the attribute Key conforming to the "service.name" - // semantic conventions. It represents the logical name of the service. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'shoppingcart' - // Note: MUST be the same for all instances of horizontally scaled - // services. If the value was not specified, SDKs MUST fallback to - // `unknown_service:` concatenated with - // [`process.executable.name`](process.md#process), e.g. - // `unknown_service:bash`. If `process.executable.name` is not available, - // the value MUST be set to `unknown_service`. - ServiceNameKey = attribute.Key("service.name") - - // ServiceVersionKey is the attribute Key conforming to the - // "service.version" semantic conventions. It represents the version string - // of the service API or implementation. The format is not defined by these - // conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2.0.0', 'a01dbef8a' - ServiceVersionKey = attribute.Key("service.version") -) - -// ServiceName returns an attribute KeyValue conforming to the -// "service.name" semantic conventions. It represents the logical name of the -// service. -func ServiceName(val string) attribute.KeyValue { - return ServiceNameKey.String(val) -} - -// ServiceVersion returns an attribute KeyValue conforming to the -// "service.version" semantic conventions. It represents the version string of -// the service API or implementation. The format is not defined by these -// conventions. -func ServiceVersion(val string) attribute.KeyValue { - return ServiceVersionKey.String(val) -} - -// A service instance. -const ( - // ServiceInstanceIDKey is the attribute Key conforming to the - // "service.instance.id" semantic conventions. It represents the string ID - // of the service instance. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'my-k8s-pod-deployment-1', - // '627cc493-f310-47de-96bd-71410b7dec09' - // Note: MUST be unique for each instance of the same - // `service.namespace,service.name` pair (in other words - // `service.namespace,service.name,service.instance.id` triplet MUST be - // globally unique). The ID helps to distinguish instances of the same - // service that exist at the same time (e.g. instances of a horizontally - // scaled service). It is preferable for the ID to be persistent and stay - // the same for the lifetime of the service instance, however it is - // acceptable that the ID is ephemeral and changes during important - // lifetime events for the service (e.g. service restarts). If the service - // has no inherent unique ID that can be used as the value of this - // attribute it is recommended to generate a random Version 1 or Version 4 - // RFC 4122 UUID (services aiming for reproducible UUIDs may also use - // Version 5, see RFC 4122 for more recommendations). - ServiceInstanceIDKey = attribute.Key("service.instance.id") - - // ServiceNamespaceKey is the attribute Key conforming to the - // "service.namespace" semantic conventions. It represents a namespace for - // `service.name`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Shop' - // Note: A string value having a meaning that helps to distinguish a group - // of services, for example the team name that owns a group of services. - // `service.name` is expected to be unique within the same namespace. If - // `service.namespace` is not specified in the Resource then `service.name` - // is expected to be unique for all services that have no explicit - // namespace defined (so the empty/unspecified namespace is simply one more - // valid namespace). Zero-length namespace string is assumed equal to - // unspecified namespace. - ServiceNamespaceKey = attribute.Key("service.namespace") -) - -// ServiceInstanceID returns an attribute KeyValue conforming to the -// "service.instance.id" semantic conventions. It represents the string ID of -// the service instance. -func ServiceInstanceID(val string) attribute.KeyValue { - return ServiceInstanceIDKey.String(val) -} - -// ServiceNamespace returns an attribute KeyValue conforming to the -// "service.namespace" semantic conventions. It represents a namespace for -// `service.name`. -func ServiceNamespace(val string) attribute.KeyValue { - return ServiceNamespaceKey.String(val) -} - -// The telemetry SDK used to capture data recorded by the instrumentation -// libraries. -const ( - // TelemetrySDKLanguageKey is the attribute Key conforming to the - // "telemetry.sdk.language" semantic conventions. It represents the - // language of the telemetry SDK. - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - TelemetrySDKLanguageKey = attribute.Key("telemetry.sdk.language") - - // TelemetrySDKNameKey is the attribute Key conforming to the - // "telemetry.sdk.name" semantic conventions. It represents the name of the - // telemetry SDK as defined above. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'opentelemetry' - // Note: The OpenTelemetry SDK MUST set the `telemetry.sdk.name` attribute - // to `opentelemetry`. - // If another SDK, like a fork or a vendor-provided implementation, is - // used, this SDK MUST set the - // `telemetry.sdk.name` attribute to the fully-qualified class or module - // name of this SDK's main entry point - // or another suitable identifier depending on the language. - // The identifier `opentelemetry` is reserved and MUST NOT be used in this - // case. - // All custom identifiers SHOULD be stable across different versions of an - // implementation. - TelemetrySDKNameKey = attribute.Key("telemetry.sdk.name") - - // TelemetrySDKVersionKey is the attribute Key conforming to the - // "telemetry.sdk.version" semantic conventions. It represents the version - // string of the telemetry SDK. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: '1.2.3' - TelemetrySDKVersionKey = attribute.Key("telemetry.sdk.version") -) - -var ( - // cpp - TelemetrySDKLanguageCPP = TelemetrySDKLanguageKey.String("cpp") - // dotnet - TelemetrySDKLanguageDotnet = TelemetrySDKLanguageKey.String("dotnet") - // erlang - TelemetrySDKLanguageErlang = TelemetrySDKLanguageKey.String("erlang") - // go - TelemetrySDKLanguageGo = TelemetrySDKLanguageKey.String("go") - // java - TelemetrySDKLanguageJava = TelemetrySDKLanguageKey.String("java") - // nodejs - TelemetrySDKLanguageNodejs = TelemetrySDKLanguageKey.String("nodejs") - // php - TelemetrySDKLanguagePHP = TelemetrySDKLanguageKey.String("php") - // python - TelemetrySDKLanguagePython = TelemetrySDKLanguageKey.String("python") - // ruby - TelemetrySDKLanguageRuby = TelemetrySDKLanguageKey.String("ruby") - // rust - TelemetrySDKLanguageRust = TelemetrySDKLanguageKey.String("rust") - // swift - TelemetrySDKLanguageSwift = TelemetrySDKLanguageKey.String("swift") - // webjs - TelemetrySDKLanguageWebjs = TelemetrySDKLanguageKey.String("webjs") -) - -// TelemetrySDKName returns an attribute KeyValue conforming to the -// "telemetry.sdk.name" semantic conventions. It represents the name of the -// telemetry SDK as defined above. -func TelemetrySDKName(val string) attribute.KeyValue { - return TelemetrySDKNameKey.String(val) -} - -// TelemetrySDKVersion returns an attribute KeyValue conforming to the -// "telemetry.sdk.version" semantic conventions. It represents the version -// string of the telemetry SDK. -func TelemetrySDKVersion(val string) attribute.KeyValue { - return TelemetrySDKVersionKey.String(val) -} - -// The telemetry SDK used to capture data recorded by the instrumentation -// libraries. -const ( - // TelemetryDistroNameKey is the attribute Key conforming to the - // "telemetry.distro.name" semantic conventions. It represents the name of - // the auto instrumentation agent or distribution, if used. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'parts-unlimited-java' - // Note: Official auto instrumentation agents and distributions SHOULD set - // the `telemetry.distro.name` attribute to - // a string starting with `opentelemetry-`, e.g. - // `opentelemetry-java-instrumentation`. - TelemetryDistroNameKey = attribute.Key("telemetry.distro.name") - - // TelemetryDistroVersionKey is the attribute Key conforming to the - // "telemetry.distro.version" semantic conventions. It represents the - // version string of the auto instrumentation agent or distribution, if - // used. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.2.3' - TelemetryDistroVersionKey = attribute.Key("telemetry.distro.version") -) - -// TelemetryDistroName returns an attribute KeyValue conforming to the -// "telemetry.distro.name" semantic conventions. It represents the name of the -// auto instrumentation agent or distribution, if used. -func TelemetryDistroName(val string) attribute.KeyValue { - return TelemetryDistroNameKey.String(val) -} - -// TelemetryDistroVersion returns an attribute KeyValue conforming to the -// "telemetry.distro.version" semantic conventions. It represents the version -// string of the auto instrumentation agent or distribution, if used. -func TelemetryDistroVersion(val string) attribute.KeyValue { - return TelemetryDistroVersionKey.String(val) -} - -// Resource describing the packaged software running the application code. Web -// engines are typically executed using process.runtime. -const ( - // WebEngineDescriptionKey is the attribute Key conforming to the - // "webengine.description" semantic conventions. It represents the - // additional description of the web engine (e.g. detailed version and - // edition information). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - - // 2.2.2.Final' - WebEngineDescriptionKey = attribute.Key("webengine.description") - - // WebEngineNameKey is the attribute Key conforming to the "webengine.name" - // semantic conventions. It represents the name of the web engine. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'WildFly' - WebEngineNameKey = attribute.Key("webengine.name") - - // WebEngineVersionKey is the attribute Key conforming to the - // "webengine.version" semantic conventions. It represents the version of - // the web engine. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '21.0.0' - WebEngineVersionKey = attribute.Key("webengine.version") -) - -// WebEngineDescription returns an attribute KeyValue conforming to the -// "webengine.description" semantic conventions. It represents the additional -// description of the web engine (e.g. detailed version and edition -// information). -func WebEngineDescription(val string) attribute.KeyValue { - return WebEngineDescriptionKey.String(val) -} - -// WebEngineName returns an attribute KeyValue conforming to the -// "webengine.name" semantic conventions. It represents the name of the web -// engine. -func WebEngineName(val string) attribute.KeyValue { - return WebEngineNameKey.String(val) -} - -// WebEngineVersion returns an attribute KeyValue conforming to the -// "webengine.version" semantic conventions. It represents the version of the -// web engine. -func WebEngineVersion(val string) attribute.KeyValue { - return WebEngineVersionKey.String(val) -} - -// Attributes used by non-OTLP exporters to represent OpenTelemetry Scope's -// concepts. -const ( - // OTelScopeNameKey is the attribute Key conforming to the - // "otel.scope.name" semantic conventions. It represents the name of the - // instrumentation scope - (`InstrumentationScope.Name` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'io.opentelemetry.contrib.mongodb' - OTelScopeNameKey = attribute.Key("otel.scope.name") - - // OTelScopeVersionKey is the attribute Key conforming to the - // "otel.scope.version" semantic conventions. It represents the version of - // the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.0.0' - OTelScopeVersionKey = attribute.Key("otel.scope.version") -) - -// OTelScopeName returns an attribute KeyValue conforming to the -// "otel.scope.name" semantic conventions. It represents the name of the -// instrumentation scope - (`InstrumentationScope.Name` in OTLP). -func OTelScopeName(val string) attribute.KeyValue { - return OTelScopeNameKey.String(val) -} - -// OTelScopeVersion returns an attribute KeyValue conforming to the -// "otel.scope.version" semantic conventions. It represents the version of the -// instrumentation scope - (`InstrumentationScope.Version` in OTLP). -func OTelScopeVersion(val string) attribute.KeyValue { - return OTelScopeVersionKey.String(val) -} - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry -// Scope's concepts. -const ( - // OTelLibraryNameKey is the attribute Key conforming to the - // "otel.library.name" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: 'io.opentelemetry.contrib.mongodb' - // Deprecated: use the `otel.scope.name` attribute. - OTelLibraryNameKey = attribute.Key("otel.library.name") - - // OTelLibraryVersionKey is the attribute Key conforming to the - // "otel.library.version" semantic conventions. - // - // Type: string - // RequirementLevel: Optional - // Stability: deprecated - // Examples: '1.0.0' - // Deprecated: use the `otel.scope.version` attribute. - OTelLibraryVersionKey = attribute.Key("otel.library.version") -) - -// OTelLibraryName returns an attribute KeyValue conforming to the -// "otel.library.name" semantic conventions. -// -// Deprecated: use the `otel.scope.name` attribute. -func OTelLibraryName(val string) attribute.KeyValue { - return OTelLibraryNameKey.String(val) -} - -// OTelLibraryVersion returns an attribute KeyValue conforming to the -// "otel.library.version" semantic conventions. -// -// Deprecated: use the `otel.scope.version` attribute. -func OTelLibraryVersion(val string) attribute.KeyValue { - return OTelLibraryVersionKey.String(val) -} diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go deleted file mode 100644 index fe80b1731..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -// SchemaURL is the schema URL that matches the version of the semantic conventions -// that this package defines. Semconv packages starting from v1.4.0 must declare -// non-empty schema URL in the form https://opentelemetry.io/schemas/ -const SchemaURL = "https://opentelemetry.io/schemas/1.24.0" diff --git a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go b/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go deleted file mode 100644 index c1718234e..000000000 --- a/e2e/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go +++ /dev/null @@ -1,1323 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Code generated from semantic convention specification. DO NOT EDIT. - -package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" - -import "go.opentelemetry.io/otel/attribute" - -// Operations that access some remote service. -const ( - // PeerServiceKey is the attribute Key conforming to the "peer.service" - // semantic conventions. It represents the - // [`service.name`](/docs/resource/README.md#service) of the remote - // service. SHOULD be equal to the actual `service.name` resource attribute - // of the remote service if any. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'AuthTokenCache' - PeerServiceKey = attribute.Key("peer.service") -) - -// PeerService returns an attribute KeyValue conforming to the -// "peer.service" semantic conventions. It represents the -// [`service.name`](/docs/resource/README.md#service) of the remote service. -// SHOULD be equal to the actual `service.name` resource attribute of the -// remote service if any. -func PeerService(val string) attribute.KeyValue { - return PeerServiceKey.String(val) -} - -// These attributes may be used for any operation with an authenticated and/or -// authorized enduser. -const ( - // EnduserIDKey is the attribute Key conforming to the "enduser.id" - // semantic conventions. It represents the username or client_id extracted - // from the access token or - // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header - // in the inbound request from outside the system. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'username' - EnduserIDKey = attribute.Key("enduser.id") - - // EnduserRoleKey is the attribute Key conforming to the "enduser.role" - // semantic conventions. It represents the actual/assumed role the client - // is making the request under extracted from token or application security - // context. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'admin' - EnduserRoleKey = attribute.Key("enduser.role") - - // EnduserScopeKey is the attribute Key conforming to the "enduser.scope" - // semantic conventions. It represents the scopes or granted authorities - // the client currently possesses extracted from token or application - // security context. The value would come from the scope associated with an - // [OAuth 2.0 Access - // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute - // value in a [SAML 2.0 - // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'read:message, write:files' - EnduserScopeKey = attribute.Key("enduser.scope") -) - -// EnduserID returns an attribute KeyValue conforming to the "enduser.id" -// semantic conventions. It represents the username or client_id extracted from -// the access token or -// [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in -// the inbound request from outside the system. -func EnduserID(val string) attribute.KeyValue { - return EnduserIDKey.String(val) -} - -// EnduserRole returns an attribute KeyValue conforming to the -// "enduser.role" semantic conventions. It represents the actual/assumed role -// the client is making the request under extracted from token or application -// security context. -func EnduserRole(val string) attribute.KeyValue { - return EnduserRoleKey.String(val) -} - -// EnduserScope returns an attribute KeyValue conforming to the -// "enduser.scope" semantic conventions. It represents the scopes or granted -// authorities the client currently possesses extracted from token or -// application security context. The value would come from the scope associated -// with an [OAuth 2.0 Access -// Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute -// value in a [SAML 2.0 -// Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). -func EnduserScope(val string) attribute.KeyValue { - return EnduserScopeKey.String(val) -} - -// These attributes allow to report this unit of code and therefore to provide -// more context about the span. -const ( - // CodeColumnKey is the attribute Key conforming to the "code.column" - // semantic conventions. It represents the column number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 16 - CodeColumnKey = attribute.Key("code.column") - - // CodeFilepathKey is the attribute Key conforming to the "code.filepath" - // semantic conventions. It represents the source code file name that - // identifies the code unit as uniquely as possible (preferably an absolute - // file path). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '/usr/local/MyApplication/content_root/app/index.php' - CodeFilepathKey = attribute.Key("code.filepath") - - // CodeFunctionKey is the attribute Key conforming to the "code.function" - // semantic conventions. It represents the method or function name, or - // equivalent (usually rightmost part of the code unit's name). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'serveRequest' - CodeFunctionKey = attribute.Key("code.function") - - // CodeLineNumberKey is the attribute Key conforming to the "code.lineno" - // semantic conventions. It represents the line number in `code.filepath` - // best representing the operation. It SHOULD point within the code unit - // named in `code.function`. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - CodeLineNumberKey = attribute.Key("code.lineno") - - // CodeNamespaceKey is the attribute Key conforming to the "code.namespace" - // semantic conventions. It represents the "namespace" within which - // `code.function` is defined. Usually the qualified class or module name, - // such that `code.namespace` + some separator + `code.function` form a - // unique identifier for the code unit. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'com.example.MyHTTPService' - CodeNamespaceKey = attribute.Key("code.namespace") - - // CodeStacktraceKey is the attribute Key conforming to the - // "code.stacktrace" semantic conventions. It represents a stacktrace as a - // string in the natural representation for the language runtime. The - // representation is to be determined and documented by each language SIG. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'at - // com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' - // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' - // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' - CodeStacktraceKey = attribute.Key("code.stacktrace") -) - -// CodeColumn returns an attribute KeyValue conforming to the "code.column" -// semantic conventions. It represents the column number in `code.filepath` -// best representing the operation. It SHOULD point within the code unit named -// in `code.function`. -func CodeColumn(val int) attribute.KeyValue { - return CodeColumnKey.Int(val) -} - -// CodeFilepath returns an attribute KeyValue conforming to the -// "code.filepath" semantic conventions. It represents the source code file -// name that identifies the code unit as uniquely as possible (preferably an -// absolute file path). -func CodeFilepath(val string) attribute.KeyValue { - return CodeFilepathKey.String(val) -} - -// CodeFunction returns an attribute KeyValue conforming to the -// "code.function" semantic conventions. It represents the method or function -// name, or equivalent (usually rightmost part of the code unit's name). -func CodeFunction(val string) attribute.KeyValue { - return CodeFunctionKey.String(val) -} - -// CodeLineNumber returns an attribute KeyValue conforming to the "code.lineno" -// semantic conventions. It represents the line number in `code.filepath` best -// representing the operation. It SHOULD point within the code unit named in -// `code.function`. -func CodeLineNumber(val int) attribute.KeyValue { - return CodeLineNumberKey.Int(val) -} - -// CodeNamespace returns an attribute KeyValue conforming to the -// "code.namespace" semantic conventions. It represents the "namespace" within -// which `code.function` is defined. Usually the qualified class or module -// name, such that `code.namespace` + some separator + `code.function` form a -// unique identifier for the code unit. -func CodeNamespace(val string) attribute.KeyValue { - return CodeNamespaceKey.String(val) -} - -// CodeStacktrace returns an attribute KeyValue conforming to the -// "code.stacktrace" semantic conventions. It represents a stacktrace as a -// string in the natural representation for the language runtime. The -// representation is to be determined and documented by each language SIG. -func CodeStacktrace(val string) attribute.KeyValue { - return CodeStacktraceKey.String(val) -} - -// These attributes may be used for any operation to store information about a -// thread that started a span. -const ( - // ThreadIDKey is the attribute Key conforming to the "thread.id" semantic - // conventions. It represents the current "managed" thread ID (as opposed - // to OS thread ID). - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 42 - ThreadIDKey = attribute.Key("thread.id") - - // ThreadNameKey is the attribute Key conforming to the "thread.name" - // semantic conventions. It represents the current thread name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'main' - ThreadNameKey = attribute.Key("thread.name") -) - -// ThreadID returns an attribute KeyValue conforming to the "thread.id" -// semantic conventions. It represents the current "managed" thread ID (as -// opposed to OS thread ID). -func ThreadID(val int) attribute.KeyValue { - return ThreadIDKey.Int(val) -} - -// ThreadName returns an attribute KeyValue conforming to the "thread.name" -// semantic conventions. It represents the current thread name. -func ThreadName(val string) attribute.KeyValue { - return ThreadNameKey.String(val) -} - -// Span attributes used by AWS Lambda (in addition to general `faas` -// attributes). -const ( - // AWSLambdaInvokedARNKey is the attribute Key conforming to the - // "aws.lambda.invoked_arn" semantic conventions. It represents the full - // invoked ARN as provided on the `Context` passed to the function - // (`Lambda-Runtime-Invoked-Function-ARN` header on the - // `/runtime/invocation/next` applicable). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' - // Note: This may be different from `cloud.resource_id` if an alias is - // involved. - AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") -) - -// AWSLambdaInvokedARN returns an attribute KeyValue conforming to the -// "aws.lambda.invoked_arn" semantic conventions. It represents the full -// invoked ARN as provided on the `Context` passed to the function -// (`Lambda-Runtime-Invoked-Function-ARN` header on the -// `/runtime/invocation/next` applicable). -func AWSLambdaInvokedARN(val string) attribute.KeyValue { - return AWSLambdaInvokedARNKey.String(val) -} - -// Attributes for CloudEvents. CloudEvents is a specification on how to define -// event data in a standard way. These attributes can be attached to spans when -// performing operations with CloudEvents, regardless of the protocol being -// used. -const ( - // CloudeventsEventIDKey is the attribute Key conforming to the - // "cloudevents.event_id" semantic conventions. It represents the - // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) - // uniquely identifies the event. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' - CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") - - // CloudeventsEventSourceKey is the attribute Key conforming to the - // "cloudevents.event_source" semantic conventions. It represents the - // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) - // identifies the context in which an event happened. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'https://github.com/cloudevents', - // '/cloudevents/spec/pull/123', 'my-service' - CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") - - // CloudeventsEventSpecVersionKey is the attribute Key conforming to the - // "cloudevents.event_spec_version" semantic conventions. It represents the - // [version of the CloudEvents - // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) - // which the event uses. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '1.0' - CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") - - // CloudeventsEventSubjectKey is the attribute Key conforming to the - // "cloudevents.event_subject" semantic conventions. It represents the - // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) - // of the event in the context of the event producer (identified by - // source). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'mynewfile.jpg' - CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") - - // CloudeventsEventTypeKey is the attribute Key conforming to the - // "cloudevents.event_type" semantic conventions. It represents the - // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) - // contains a value describing the type of event related to the originating - // occurrence. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'com.github.pull_request.opened', - // 'com.example.object.deleted.v2' - CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") -) - -// CloudeventsEventID returns an attribute KeyValue conforming to the -// "cloudevents.event_id" semantic conventions. It represents the -// [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) -// uniquely identifies the event. -func CloudeventsEventID(val string) attribute.KeyValue { - return CloudeventsEventIDKey.String(val) -} - -// CloudeventsEventSource returns an attribute KeyValue conforming to the -// "cloudevents.event_source" semantic conventions. It represents the -// [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) -// identifies the context in which an event happened. -func CloudeventsEventSource(val string) attribute.KeyValue { - return CloudeventsEventSourceKey.String(val) -} - -// CloudeventsEventSpecVersion returns an attribute KeyValue conforming to -// the "cloudevents.event_spec_version" semantic conventions. It represents the -// [version of the CloudEvents -// specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) -// which the event uses. -func CloudeventsEventSpecVersion(val string) attribute.KeyValue { - return CloudeventsEventSpecVersionKey.String(val) -} - -// CloudeventsEventSubject returns an attribute KeyValue conforming to the -// "cloudevents.event_subject" semantic conventions. It represents the -// [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) -// of the event in the context of the event producer (identified by source). -func CloudeventsEventSubject(val string) attribute.KeyValue { - return CloudeventsEventSubjectKey.String(val) -} - -// CloudeventsEventType returns an attribute KeyValue conforming to the -// "cloudevents.event_type" semantic conventions. It represents the -// [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) -// contains a value describing the type of event related to the originating -// occurrence. -func CloudeventsEventType(val string) attribute.KeyValue { - return CloudeventsEventTypeKey.String(val) -} - -// Semantic conventions for the OpenTracing Shim -const ( - // OpentracingRefTypeKey is the attribute Key conforming to the - // "opentracing.ref_type" semantic conventions. It represents the - // parent-child Reference type - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Note: The causal relationship between a child Span and a parent Span. - OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") -) - -var ( - // The parent Span depends on the child Span in some capacity - OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") - // The parent Span doesn't depend in any way on the result of the child Span - OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") -) - -// Span attributes used by non-OTLP exporters to represent OpenTelemetry Span's -// concepts. -const ( - // OTelStatusCodeKey is the attribute Key conforming to the - // "otel.status_code" semantic conventions. It represents the name of the - // code, either "OK" or "ERROR". MUST NOT be set if the status code is - // UNSET. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - OTelStatusCodeKey = attribute.Key("otel.status_code") - - // OTelStatusDescriptionKey is the attribute Key conforming to the - // "otel.status_description" semantic conventions. It represents the - // description of the Status if it has a value, otherwise not set. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'resource not found' - OTelStatusDescriptionKey = attribute.Key("otel.status_description") -) - -var ( - // The operation has been validated by an Application developer or Operator to have completed successfully - OTelStatusCodeOk = OTelStatusCodeKey.String("OK") - // The operation contains an error - OTelStatusCodeError = OTelStatusCodeKey.String("ERROR") -) - -// OTelStatusDescription returns an attribute KeyValue conforming to the -// "otel.status_description" semantic conventions. It represents the -// description of the Status if it has a value, otherwise not set. -func OTelStatusDescription(val string) attribute.KeyValue { - return OTelStatusDescriptionKey.String(val) -} - -// This semantic convention describes an instance of a function that runs -// without provisioning or managing of servers (also known as serverless -// functions or Function as a Service (FaaS)) with spans. -const ( - // FaaSInvocationIDKey is the attribute Key conforming to the - // "faas.invocation_id" semantic conventions. It represents the invocation - // ID of the current function invocation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'af9d5aa4-a685-4c5f-a22b-444f80b3cc28' - FaaSInvocationIDKey = attribute.Key("faas.invocation_id") -) - -// FaaSInvocationID returns an attribute KeyValue conforming to the -// "faas.invocation_id" semantic conventions. It represents the invocation ID -// of the current function invocation. -func FaaSInvocationID(val string) attribute.KeyValue { - return FaaSInvocationIDKey.String(val) -} - -// Semantic Convention for FaaS triggered as a response to some data source -// operation such as a database or filesystem read/write. -const ( - // FaaSDocumentCollectionKey is the attribute Key conforming to the - // "faas.document.collection" semantic conventions. It represents the name - // of the source on which the triggering operation was performed. For - // example, in Cloud Storage or S3 corresponds to the bucket name, and in - // Cosmos DB to the database name. - // - // Type: string - // RequirementLevel: Required - // Stability: experimental - // Examples: 'myBucketName', 'myDBName' - FaaSDocumentCollectionKey = attribute.Key("faas.document.collection") - - // FaaSDocumentNameKey is the attribute Key conforming to the - // "faas.document.name" semantic conventions. It represents the document - // name/table subjected to the operation. For example, in Cloud Storage or - // S3 is the name of the file, and in Cosmos DB the table name. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'myFile.txt', 'myTableName' - FaaSDocumentNameKey = attribute.Key("faas.document.name") - - // FaaSDocumentOperationKey is the attribute Key conforming to the - // "faas.document.operation" semantic conventions. It represents the - // describes the type of the operation that was performed on the data. - // - // Type: Enum - // RequirementLevel: Required - // Stability: experimental - FaaSDocumentOperationKey = attribute.Key("faas.document.operation") - - // FaaSDocumentTimeKey is the attribute Key conforming to the - // "faas.document.time" semantic conventions. It represents a string - // containing the time when the data was accessed in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2020-01-23T13:47:06Z' - FaaSDocumentTimeKey = attribute.Key("faas.document.time") -) - -var ( - // When a new object is created - FaaSDocumentOperationInsert = FaaSDocumentOperationKey.String("insert") - // When an object is modified - FaaSDocumentOperationEdit = FaaSDocumentOperationKey.String("edit") - // When an object is deleted - FaaSDocumentOperationDelete = FaaSDocumentOperationKey.String("delete") -) - -// FaaSDocumentCollection returns an attribute KeyValue conforming to the -// "faas.document.collection" semantic conventions. It represents the name of -// the source on which the triggering operation was performed. For example, in -// Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the -// database name. -func FaaSDocumentCollection(val string) attribute.KeyValue { - return FaaSDocumentCollectionKey.String(val) -} - -// FaaSDocumentName returns an attribute KeyValue conforming to the -// "faas.document.name" semantic conventions. It represents the document -// name/table subjected to the operation. For example, in Cloud Storage or S3 -// is the name of the file, and in Cosmos DB the table name. -func FaaSDocumentName(val string) attribute.KeyValue { - return FaaSDocumentNameKey.String(val) -} - -// FaaSDocumentTime returns an attribute KeyValue conforming to the -// "faas.document.time" semantic conventions. It represents a string containing -// the time when the data was accessed in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSDocumentTime(val string) attribute.KeyValue { - return FaaSDocumentTimeKey.String(val) -} - -// Semantic Convention for FaaS scheduled to be executed regularly. -const ( - // FaaSCronKey is the attribute Key conforming to the "faas.cron" semantic - // conventions. It represents a string containing the schedule period as - // [Cron - // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '0/5 * * * ? *' - FaaSCronKey = attribute.Key("faas.cron") - - // FaaSTimeKey is the attribute Key conforming to the "faas.time" semantic - // conventions. It represents a string containing the function invocation - // time in the [ISO - // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '2020-01-23T13:47:06Z' - FaaSTimeKey = attribute.Key("faas.time") -) - -// FaaSCron returns an attribute KeyValue conforming to the "faas.cron" -// semantic conventions. It represents a string containing the schedule period -// as [Cron -// Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). -func FaaSCron(val string) attribute.KeyValue { - return FaaSCronKey.String(val) -} - -// FaaSTime returns an attribute KeyValue conforming to the "faas.time" -// semantic conventions. It represents a string containing the function -// invocation time in the [ISO -// 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format -// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). -func FaaSTime(val string) attribute.KeyValue { - return FaaSTimeKey.String(val) -} - -// Contains additional attributes for incoming FaaS spans. -const ( - // FaaSColdstartKey is the attribute Key conforming to the "faas.coldstart" - // semantic conventions. It represents a boolean that is true if the - // serverless function is executed for the first time (aka cold-start). - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - FaaSColdstartKey = attribute.Key("faas.coldstart") -) - -// FaaSColdstart returns an attribute KeyValue conforming to the -// "faas.coldstart" semantic conventions. It represents a boolean that is true -// if the serverless function is executed for the first time (aka cold-start). -func FaaSColdstart(val bool) attribute.KeyValue { - return FaaSColdstartKey.Bool(val) -} - -// The `aws` conventions apply to operations using the AWS SDK. They map -// request or response parameters in AWS SDK API calls to attributes on a Span. -// The conventions have been collected over time based on feedback from AWS -// users of tracing and will continue to evolve as new interesting conventions -// are found. -// Some descriptions are also provided for populating general OpenTelemetry -// semantic conventions based on these APIs. -const ( - // AWSRequestIDKey is the attribute Key conforming to the "aws.request_id" - // semantic conventions. It represents the AWS request ID as returned in - // the response headers `x-amz-request-id` or `x-amz-requestid`. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '79b9da39-b7ae-508a-a6bc-864b2829c622', 'C9ER4AJX75574TDJ' - AWSRequestIDKey = attribute.Key("aws.request_id") -) - -// AWSRequestID returns an attribute KeyValue conforming to the -// "aws.request_id" semantic conventions. It represents the AWS request ID as -// returned in the response headers `x-amz-request-id` or `x-amz-requestid`. -func AWSRequestID(val string) attribute.KeyValue { - return AWSRequestIDKey.String(val) -} - -// Attributes that exist for multiple DynamoDB request types. -const ( - // AWSDynamoDBAttributesToGetKey is the attribute Key conforming to the - // "aws.dynamodb.attributes_to_get" semantic conventions. It represents the - // value of the `AttributesToGet` request parameter. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'lives', 'id' - AWSDynamoDBAttributesToGetKey = attribute.Key("aws.dynamodb.attributes_to_get") - - // AWSDynamoDBConsistentReadKey is the attribute Key conforming to the - // "aws.dynamodb.consistent_read" semantic conventions. It represents the - // value of the `ConsistentRead` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - AWSDynamoDBConsistentReadKey = attribute.Key("aws.dynamodb.consistent_read") - - // AWSDynamoDBConsumedCapacityKey is the attribute Key conforming to the - // "aws.dynamodb.consumed_capacity" semantic conventions. It represents the - // JSON-serialized value of each item in the `ConsumedCapacity` response - // field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "CapacityUnits": number, "GlobalSecondaryIndexes": { - // "string" : { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "LocalSecondaryIndexes": { "string" : - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }, "ReadCapacityUnits": number, "Table": - // { "CapacityUnits": number, "ReadCapacityUnits": number, - // "WriteCapacityUnits": number }, "TableName": "string", - // "WriteCapacityUnits": number }' - AWSDynamoDBConsumedCapacityKey = attribute.Key("aws.dynamodb.consumed_capacity") - - // AWSDynamoDBIndexNameKey is the attribute Key conforming to the - // "aws.dynamodb.index_name" semantic conventions. It represents the value - // of the `IndexName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'name_to_group' - AWSDynamoDBIndexNameKey = attribute.Key("aws.dynamodb.index_name") - - // AWSDynamoDBItemCollectionMetricsKey is the attribute Key conforming to - // the "aws.dynamodb.item_collection_metrics" semantic conventions. It - // represents the JSON-serialized value of the `ItemCollectionMetrics` - // response field. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "string" : [ { "ItemCollectionKey": { "string" : { "B": - // blob, "BOOL": boolean, "BS": [ blob ], "L": [ "AttributeValue" ], "M": { - // "string" : "AttributeValue" }, "N": "string", "NS": [ "string" ], - // "NULL": boolean, "S": "string", "SS": [ "string" ] } }, - // "SizeEstimateRangeGB": [ number ] } ] }' - AWSDynamoDBItemCollectionMetricsKey = attribute.Key("aws.dynamodb.item_collection_metrics") - - // AWSDynamoDBLimitKey is the attribute Key conforming to the - // "aws.dynamodb.limit" semantic conventions. It represents the value of - // the `Limit` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBLimitKey = attribute.Key("aws.dynamodb.limit") - - // AWSDynamoDBProjectionKey is the attribute Key conforming to the - // "aws.dynamodb.projection" semantic conventions. It represents the value - // of the `ProjectionExpression` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Title', 'Title, Price, Color', 'Title, Description, - // RelatedItems, ProductReviews' - AWSDynamoDBProjectionKey = attribute.Key("aws.dynamodb.projection") - - // AWSDynamoDBProvisionedReadCapacityKey is the attribute Key conforming to - // the "aws.dynamodb.provisioned_read_capacity" semantic conventions. It - // represents the value of the `ProvisionedThroughput.ReadCapacityUnits` - // request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedReadCapacityKey = attribute.Key("aws.dynamodb.provisioned_read_capacity") - - // AWSDynamoDBProvisionedWriteCapacityKey is the attribute Key conforming - // to the "aws.dynamodb.provisioned_write_capacity" semantic conventions. - // It represents the value of the - // `ProvisionedThroughput.WriteCapacityUnits` request parameter. - // - // Type: double - // RequirementLevel: Optional - // Stability: experimental - // Examples: 1.0, 2.0 - AWSDynamoDBProvisionedWriteCapacityKey = attribute.Key("aws.dynamodb.provisioned_write_capacity") - - // AWSDynamoDBSelectKey is the attribute Key conforming to the - // "aws.dynamodb.select" semantic conventions. It represents the value of - // the `Select` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'ALL_ATTRIBUTES', 'COUNT' - AWSDynamoDBSelectKey = attribute.Key("aws.dynamodb.select") - - // AWSDynamoDBTableNamesKey is the attribute Key conforming to the - // "aws.dynamodb.table_names" semantic conventions. It represents the keys - // in the `RequestItems` object field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Users', 'Cats' - AWSDynamoDBTableNamesKey = attribute.Key("aws.dynamodb.table_names") -) - -// AWSDynamoDBAttributesToGet returns an attribute KeyValue conforming to -// the "aws.dynamodb.attributes_to_get" semantic conventions. It represents the -// value of the `AttributesToGet` request parameter. -func AWSDynamoDBAttributesToGet(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributesToGetKey.StringSlice(val) -} - -// AWSDynamoDBConsistentRead returns an attribute KeyValue conforming to the -// "aws.dynamodb.consistent_read" semantic conventions. It represents the value -// of the `ConsistentRead` request parameter. -func AWSDynamoDBConsistentRead(val bool) attribute.KeyValue { - return AWSDynamoDBConsistentReadKey.Bool(val) -} - -// AWSDynamoDBConsumedCapacity returns an attribute KeyValue conforming to -// the "aws.dynamodb.consumed_capacity" semantic conventions. It represents the -// JSON-serialized value of each item in the `ConsumedCapacity` response field. -func AWSDynamoDBConsumedCapacity(val ...string) attribute.KeyValue { - return AWSDynamoDBConsumedCapacityKey.StringSlice(val) -} - -// AWSDynamoDBIndexName returns an attribute KeyValue conforming to the -// "aws.dynamodb.index_name" semantic conventions. It represents the value of -// the `IndexName` request parameter. -func AWSDynamoDBIndexName(val string) attribute.KeyValue { - return AWSDynamoDBIndexNameKey.String(val) -} - -// AWSDynamoDBItemCollectionMetrics returns an attribute KeyValue conforming -// to the "aws.dynamodb.item_collection_metrics" semantic conventions. It -// represents the JSON-serialized value of the `ItemCollectionMetrics` response -// field. -func AWSDynamoDBItemCollectionMetrics(val string) attribute.KeyValue { - return AWSDynamoDBItemCollectionMetricsKey.String(val) -} - -// AWSDynamoDBLimit returns an attribute KeyValue conforming to the -// "aws.dynamodb.limit" semantic conventions. It represents the value of the -// `Limit` request parameter. -func AWSDynamoDBLimit(val int) attribute.KeyValue { - return AWSDynamoDBLimitKey.Int(val) -} - -// AWSDynamoDBProjection returns an attribute KeyValue conforming to the -// "aws.dynamodb.projection" semantic conventions. It represents the value of -// the `ProjectionExpression` request parameter. -func AWSDynamoDBProjection(val string) attribute.KeyValue { - return AWSDynamoDBProjectionKey.String(val) -} - -// AWSDynamoDBProvisionedReadCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_read_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.ReadCapacityUnits` request parameter. -func AWSDynamoDBProvisionedReadCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedReadCapacityKey.Float64(val) -} - -// AWSDynamoDBProvisionedWriteCapacity returns an attribute KeyValue -// conforming to the "aws.dynamodb.provisioned_write_capacity" semantic -// conventions. It represents the value of the -// `ProvisionedThroughput.WriteCapacityUnits` request parameter. -func AWSDynamoDBProvisionedWriteCapacity(val float64) attribute.KeyValue { - return AWSDynamoDBProvisionedWriteCapacityKey.Float64(val) -} - -// AWSDynamoDBSelect returns an attribute KeyValue conforming to the -// "aws.dynamodb.select" semantic conventions. It represents the value of the -// `Select` request parameter. -func AWSDynamoDBSelect(val string) attribute.KeyValue { - return AWSDynamoDBSelectKey.String(val) -} - -// AWSDynamoDBTableNames returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_names" semantic conventions. It represents the keys in -// the `RequestItems` object field. -func AWSDynamoDBTableNames(val ...string) attribute.KeyValue { - return AWSDynamoDBTableNamesKey.StringSlice(val) -} - -// DynamoDB.CreateTable -const ( - // AWSDynamoDBGlobalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.global_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `GlobalSecondaryIndexes` request field - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "IndexName": "string", "KeySchema": [ { "AttributeName": - // "string", "KeyType": "string" } ], "Projection": { "NonKeyAttributes": [ - // "string" ], "ProjectionType": "string" }, "ProvisionedThroughput": { - // "ReadCapacityUnits": number, "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexesKey = attribute.Key("aws.dynamodb.global_secondary_indexes") - - // AWSDynamoDBLocalSecondaryIndexesKey is the attribute Key conforming to - // the "aws.dynamodb.local_secondary_indexes" semantic conventions. It - // represents the JSON-serialized value of each item of the - // `LocalSecondaryIndexes` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "IndexARN": "string", "IndexName": "string", - // "IndexSizeBytes": number, "ItemCount": number, "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" } }' - AWSDynamoDBLocalSecondaryIndexesKey = attribute.Key("aws.dynamodb.local_secondary_indexes") -) - -// AWSDynamoDBGlobalSecondaryIndexes returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_indexes" semantic -// conventions. It represents the JSON-serialized value of each item of the -// `GlobalSecondaryIndexes` request field -func AWSDynamoDBGlobalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexesKey.StringSlice(val) -} - -// AWSDynamoDBLocalSecondaryIndexes returns an attribute KeyValue conforming -// to the "aws.dynamodb.local_secondary_indexes" semantic conventions. It -// represents the JSON-serialized value of each item of the -// `LocalSecondaryIndexes` request field. -func AWSDynamoDBLocalSecondaryIndexes(val ...string) attribute.KeyValue { - return AWSDynamoDBLocalSecondaryIndexesKey.StringSlice(val) -} - -// DynamoDB.ListTables -const ( - // AWSDynamoDBExclusiveStartTableKey is the attribute Key conforming to the - // "aws.dynamodb.exclusive_start_table" semantic conventions. It represents - // the value of the `ExclusiveStartTableName` request parameter. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'Users', 'CatsTable' - AWSDynamoDBExclusiveStartTableKey = attribute.Key("aws.dynamodb.exclusive_start_table") - - // AWSDynamoDBTableCountKey is the attribute Key conforming to the - // "aws.dynamodb.table_count" semantic conventions. It represents the the - // number of items in the `TableNames` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 20 - AWSDynamoDBTableCountKey = attribute.Key("aws.dynamodb.table_count") -) - -// AWSDynamoDBExclusiveStartTable returns an attribute KeyValue conforming -// to the "aws.dynamodb.exclusive_start_table" semantic conventions. It -// represents the value of the `ExclusiveStartTableName` request parameter. -func AWSDynamoDBExclusiveStartTable(val string) attribute.KeyValue { - return AWSDynamoDBExclusiveStartTableKey.String(val) -} - -// AWSDynamoDBTableCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.table_count" semantic conventions. It represents the the -// number of items in the `TableNames` response parameter. -func AWSDynamoDBTableCount(val int) attribute.KeyValue { - return AWSDynamoDBTableCountKey.Int(val) -} - -// DynamoDB.Query -const ( - // AWSDynamoDBScanForwardKey is the attribute Key conforming to the - // "aws.dynamodb.scan_forward" semantic conventions. It represents the - // value of the `ScanIndexForward` request parameter. - // - // Type: boolean - // RequirementLevel: Optional - // Stability: experimental - AWSDynamoDBScanForwardKey = attribute.Key("aws.dynamodb.scan_forward") -) - -// AWSDynamoDBScanForward returns an attribute KeyValue conforming to the -// "aws.dynamodb.scan_forward" semantic conventions. It represents the value of -// the `ScanIndexForward` request parameter. -func AWSDynamoDBScanForward(val bool) attribute.KeyValue { - return AWSDynamoDBScanForwardKey.Bool(val) -} - -// DynamoDB.Scan -const ( - // AWSDynamoDBCountKey is the attribute Key conforming to the - // "aws.dynamodb.count" semantic conventions. It represents the value of - // the `Count` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBCountKey = attribute.Key("aws.dynamodb.count") - - // AWSDynamoDBScannedCountKey is the attribute Key conforming to the - // "aws.dynamodb.scanned_count" semantic conventions. It represents the - // value of the `ScannedCount` response parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 50 - AWSDynamoDBScannedCountKey = attribute.Key("aws.dynamodb.scanned_count") - - // AWSDynamoDBSegmentKey is the attribute Key conforming to the - // "aws.dynamodb.segment" semantic conventions. It represents the value of - // the `Segment` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 10 - AWSDynamoDBSegmentKey = attribute.Key("aws.dynamodb.segment") - - // AWSDynamoDBTotalSegmentsKey is the attribute Key conforming to the - // "aws.dynamodb.total_segments" semantic conventions. It represents the - // value of the `TotalSegments` request parameter. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 100 - AWSDynamoDBTotalSegmentsKey = attribute.Key("aws.dynamodb.total_segments") -) - -// AWSDynamoDBCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.count" semantic conventions. It represents the value of the -// `Count` response parameter. -func AWSDynamoDBCount(val int) attribute.KeyValue { - return AWSDynamoDBCountKey.Int(val) -} - -// AWSDynamoDBScannedCount returns an attribute KeyValue conforming to the -// "aws.dynamodb.scanned_count" semantic conventions. It represents the value -// of the `ScannedCount` response parameter. -func AWSDynamoDBScannedCount(val int) attribute.KeyValue { - return AWSDynamoDBScannedCountKey.Int(val) -} - -// AWSDynamoDBSegment returns an attribute KeyValue conforming to the -// "aws.dynamodb.segment" semantic conventions. It represents the value of the -// `Segment` request parameter. -func AWSDynamoDBSegment(val int) attribute.KeyValue { - return AWSDynamoDBSegmentKey.Int(val) -} - -// AWSDynamoDBTotalSegments returns an attribute KeyValue conforming to the -// "aws.dynamodb.total_segments" semantic conventions. It represents the value -// of the `TotalSegments` request parameter. -func AWSDynamoDBTotalSegments(val int) attribute.KeyValue { - return AWSDynamoDBTotalSegmentsKey.Int(val) -} - -// DynamoDB.UpdateTable -const ( - // AWSDynamoDBAttributeDefinitionsKey is the attribute Key conforming to - // the "aws.dynamodb.attribute_definitions" semantic conventions. It - // represents the JSON-serialized value of each item in the - // `AttributeDefinitions` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "AttributeName": "string", "AttributeType": "string" }' - AWSDynamoDBAttributeDefinitionsKey = attribute.Key("aws.dynamodb.attribute_definitions") - - // AWSDynamoDBGlobalSecondaryIndexUpdatesKey is the attribute Key - // conforming to the "aws.dynamodb.global_secondary_index_updates" semantic - // conventions. It represents the JSON-serialized value of each item in the - // the `GlobalSecondaryIndexUpdates` request field. - // - // Type: string[] - // RequirementLevel: Optional - // Stability: experimental - // Examples: '{ "Create": { "IndexName": "string", "KeySchema": [ { - // "AttributeName": "string", "KeyType": "string" } ], "Projection": { - // "NonKeyAttributes": [ "string" ], "ProjectionType": "string" }, - // "ProvisionedThroughput": { "ReadCapacityUnits": number, - // "WriteCapacityUnits": number } }' - AWSDynamoDBGlobalSecondaryIndexUpdatesKey = attribute.Key("aws.dynamodb.global_secondary_index_updates") -) - -// AWSDynamoDBAttributeDefinitions returns an attribute KeyValue conforming -// to the "aws.dynamodb.attribute_definitions" semantic conventions. It -// represents the JSON-serialized value of each item in the -// `AttributeDefinitions` request field. -func AWSDynamoDBAttributeDefinitions(val ...string) attribute.KeyValue { - return AWSDynamoDBAttributeDefinitionsKey.StringSlice(val) -} - -// AWSDynamoDBGlobalSecondaryIndexUpdates returns an attribute KeyValue -// conforming to the "aws.dynamodb.global_secondary_index_updates" semantic -// conventions. It represents the JSON-serialized value of each item in the the -// `GlobalSecondaryIndexUpdates` request field. -func AWSDynamoDBGlobalSecondaryIndexUpdates(val ...string) attribute.KeyValue { - return AWSDynamoDBGlobalSecondaryIndexUpdatesKey.StringSlice(val) -} - -// Attributes that exist for S3 request types. -const ( - // AWSS3BucketKey is the attribute Key conforming to the "aws.s3.bucket" - // semantic conventions. It represents the S3 bucket name the request - // refers to. Corresponds to the `--bucket` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'some-bucket-name' - // Note: The `bucket` attribute is applicable to all S3 operations that - // reference a bucket, i.e. that require the bucket name as a mandatory - // parameter. - // This applies to almost all S3 operations except `list-buckets`. - AWSS3BucketKey = attribute.Key("aws.s3.bucket") - - // AWSS3CopySourceKey is the attribute Key conforming to the - // "aws.s3.copy_source" semantic conventions. It represents the source - // object (in the form `bucket`/`key`) for the copy operation. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'someFile.yml' - // Note: The `copy_source` attribute applies to S3 copy operations and - // corresponds to the `--copy-source` parameter - // of the [copy-object operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html). - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3CopySourceKey = attribute.Key("aws.s3.copy_source") - - // AWSS3DeleteKey is the attribute Key conforming to the "aws.s3.delete" - // semantic conventions. It represents the delete request container that - // specifies the objects to be deleted. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: - // 'Objects=[{Key=string,VersionID=string},{Key=string,VersionID=string}],Quiet=boolean' - // Note: The `delete` attribute is only applicable to the - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // operation. - // The `delete` attribute corresponds to the `--delete` parameter of the - // [delete-objects operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-objects.html). - AWSS3DeleteKey = attribute.Key("aws.s3.delete") - - // AWSS3KeyKey is the attribute Key conforming to the "aws.s3.key" semantic - // conventions. It represents the S3 object key the request refers to. - // Corresponds to the `--key` parameter of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // operations. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'someFile.yml' - // Note: The `key` attribute is applicable to all object-related S3 - // operations, i.e. that require the object key as a mandatory parameter. - // This applies in particular to the following operations: - // - // - - // [copy-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html) - // - - // [delete-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html) - // - - // [get-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html) - // - - // [head-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/head-object.html) - // - - // [put-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html) - // - - // [restore-object](https://docs.aws.amazon.com/cli/latest/reference/s3api/restore-object.html) - // - - // [select-object-content](https://docs.aws.amazon.com/cli/latest/reference/s3api/select-object-content.html) - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [create-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/create-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3KeyKey = attribute.Key("aws.s3.key") - - // AWSS3PartNumberKey is the attribute Key conforming to the - // "aws.s3.part_number" semantic conventions. It represents the part number - // of the part being uploaded in a multipart-upload operation. This is a - // positive integer between 1 and 10,000. - // - // Type: int - // RequirementLevel: Optional - // Stability: experimental - // Examples: 3456 - // Note: The `part_number` attribute is only applicable to the - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // and - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - // operations. - // The `part_number` attribute corresponds to the `--part-number` parameter - // of the - // [upload-part operation within the S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html). - AWSS3PartNumberKey = attribute.Key("aws.s3.part_number") - - // AWSS3UploadIDKey is the attribute Key conforming to the - // "aws.s3.upload_id" semantic conventions. It represents the upload ID - // that identifies the multipart upload. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'dfRtDYWFbkRONycy.Yxwh66Yjlx.cph0gtNBtJ' - // Note: The `upload_id` attribute applies to S3 multipart-upload - // operations and corresponds to the `--upload-id` parameter - // of the [S3 - // API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) - // multipart operations. - // This applies in particular to the following operations: - // - // - - // [abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) - // - - // [complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/complete-multipart-upload.html) - // - - // [list-parts](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-parts.html) - // - - // [upload-part](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part.html) - // - - // [upload-part-copy](https://docs.aws.amazon.com/cli/latest/reference/s3api/upload-part-copy.html) - AWSS3UploadIDKey = attribute.Key("aws.s3.upload_id") -) - -// AWSS3Bucket returns an attribute KeyValue conforming to the -// "aws.s3.bucket" semantic conventions. It represents the S3 bucket name the -// request refers to. Corresponds to the `--bucket` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Bucket(val string) attribute.KeyValue { - return AWSS3BucketKey.String(val) -} - -// AWSS3CopySource returns an attribute KeyValue conforming to the -// "aws.s3.copy_source" semantic conventions. It represents the source object -// (in the form `bucket`/`key`) for the copy operation. -func AWSS3CopySource(val string) attribute.KeyValue { - return AWSS3CopySourceKey.String(val) -} - -// AWSS3Delete returns an attribute KeyValue conforming to the -// "aws.s3.delete" semantic conventions. It represents the delete request -// container that specifies the objects to be deleted. -func AWSS3Delete(val string) attribute.KeyValue { - return AWSS3DeleteKey.String(val) -} - -// AWSS3Key returns an attribute KeyValue conforming to the "aws.s3.key" -// semantic conventions. It represents the S3 object key the request refers to. -// Corresponds to the `--key` parameter of the [S3 -// API](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) -// operations. -func AWSS3Key(val string) attribute.KeyValue { - return AWSS3KeyKey.String(val) -} - -// AWSS3PartNumber returns an attribute KeyValue conforming to the -// "aws.s3.part_number" semantic conventions. It represents the part number of -// the part being uploaded in a multipart-upload operation. This is a positive -// integer between 1 and 10,000. -func AWSS3PartNumber(val int) attribute.KeyValue { - return AWSS3PartNumberKey.Int(val) -} - -// AWSS3UploadID returns an attribute KeyValue conforming to the -// "aws.s3.upload_id" semantic conventions. It represents the upload ID that -// identifies the multipart upload. -func AWSS3UploadID(val string) attribute.KeyValue { - return AWSS3UploadIDKey.String(val) -} - -// Semantic conventions to apply when instrumenting the GraphQL implementation. -// They map GraphQL operations to attributes on a Span. -const ( - // GraphqlDocumentKey is the attribute Key conforming to the - // "graphql.document" semantic conventions. It represents the GraphQL - // document being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'query findBookByID { bookByID(id: ?) { name } }' - // Note: The value may be sanitized to exclude sensitive information. - GraphqlDocumentKey = attribute.Key("graphql.document") - - // GraphqlOperationNameKey is the attribute Key conforming to the - // "graphql.operation.name" semantic conventions. It represents the name of - // the operation being executed. - // - // Type: string - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'findBookByID' - GraphqlOperationNameKey = attribute.Key("graphql.operation.name") - - // GraphqlOperationTypeKey is the attribute Key conforming to the - // "graphql.operation.type" semantic conventions. It represents the type of - // the operation being executed. - // - // Type: Enum - // RequirementLevel: Optional - // Stability: experimental - // Examples: 'query', 'mutation', 'subscription' - GraphqlOperationTypeKey = attribute.Key("graphql.operation.type") -) - -var ( - // GraphQL query - GraphqlOperationTypeQuery = GraphqlOperationTypeKey.String("query") - // GraphQL mutation - GraphqlOperationTypeMutation = GraphqlOperationTypeKey.String("mutation") - // GraphQL subscription - GraphqlOperationTypeSubscription = GraphqlOperationTypeKey.String("subscription") -) - -// GraphqlDocument returns an attribute KeyValue conforming to the -// "graphql.document" semantic conventions. It represents the GraphQL document -// being executed. -func GraphqlDocument(val string) attribute.KeyValue { - return GraphqlDocumentKey.String(val) -} - -// GraphqlOperationName returns an attribute KeyValue conforming to the -// "graphql.operation.name" semantic conventions. It represents the name of the -// operation being executed. -func GraphqlOperationName(val string) attribute.KeyValue { - return GraphqlOperationNameKey.String(val) -} diff --git a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go index 4a9fce53c..db7806cb9 100644 --- a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go +++ b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go @@ -1159,6 +1159,13 @@ type SelectiveGapicGeneration struct { // An allowlist of the fully qualified names of RPCs that should be included // on public client surfaces. Methods []string `protobuf:"bytes,1,rep,name=methods,proto3" json:"methods,omitempty"` + // Setting this to true indicates to the client generators that methods + // that would be excluded from the generation should instead be generated + // in a way that indicates these methods should not be consumed by + // end users. How this is expressed is up to individual language + // implementations to decide. Some examples may be: added annotations, + // obfuscated identifiers, or other language idiomatic patterns. + GenerateOmittedAsInternal bool `protobuf:"varint,2,opt,name=generate_omitted_as_internal,json=generateOmittedAsInternal,proto3" json:"generate_omitted_as_internal,omitempty"` } func (x *SelectiveGapicGeneration) Reset() { @@ -1200,6 +1207,13 @@ func (x *SelectiveGapicGeneration) GetMethods() []string { return nil } +func (x *SelectiveGapicGeneration) GetGenerateOmittedAsInternal() bool { + if x != nil { + return x.GenerateOmittedAsInternal + } + return false +} + // Experimental features to be included during client library generation. // These fields will be deprecated once the feature graduates and is enabled // by default. @@ -1218,6 +1232,11 @@ type PythonSettings_ExperimentalFeatures struct { // enabled by default 1 month after launching the feature in preview // packages. ProtobufPythonicTypesEnabled bool `protobuf:"varint,2,opt,name=protobuf_pythonic_types_enabled,json=protobufPythonicTypesEnabled,proto3" json:"protobuf_pythonic_types_enabled,omitempty"` + // Disables generation of an unversioned Python package for this client + // library. This means that the module names will need to be versioned in + // import statements. For example `import google.cloud.library_v2` instead + // of `import google.cloud.library`. + UnversionedPackageDisabled bool `protobuf:"varint,3,opt,name=unversioned_package_disabled,json=unversionedPackageDisabled,proto3" json:"unversioned_package_disabled,omitempty"` } func (x *PythonSettings_ExperimentalFeatures) Reset() { @@ -1266,6 +1285,13 @@ func (x *PythonSettings_ExperimentalFeatures) GetProtobufPythonicTypesEnabled() return false } +func (x *PythonSettings_ExperimentalFeatures) GetUnversionedPackageDisabled() bool { + if x != nil { + return x.UnversionedPackageDisabled + } + return false +} + // Describes settings to use when generating API methods that use the // long-running operation pattern. // All default values below are from those used in the client library @@ -1619,7 +1645,7 @@ var file_google_api_client_proto_rawDesc = []byte{ 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, - 0x6e, 0x22, 0xc5, 0x02, 0x0a, 0x0e, 0x50, 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x53, 0x65, 0x74, 0x74, + 0x6e, 0x22, 0x87, 0x03, 0x0a, 0x0e, 0x50, 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, @@ -1630,7 +1656,7 @@ var file_google_api_client_proto_rawDesc = []byte{ 0x68, 0x6f, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x45, 0x78, 0x70, 0x65, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x52, 0x14, 0x65, 0x78, 0x70, 0x65, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x46, 0x65, - 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x1a, 0x90, 0x01, 0x0a, 0x14, 0x45, 0x78, 0x70, 0x65, 0x72, + 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x1a, 0xd2, 0x01, 0x0a, 0x14, 0x45, 0x78, 0x70, 0x65, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x31, 0x0a, 0x15, 0x72, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x73, 0x79, 0x6e, 0x63, 0x5f, 0x69, 0x6f, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x12, @@ -1639,140 +1665,148 @@ var file_google_api_client_proto_rawDesc = []byte{ 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x69, 0x63, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x5f, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x50, 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x69, 0x63, 0x54, 0x79, 0x70, - 0x65, 0x73, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x22, 0x4a, 0x0a, 0x0c, 0x4e, 0x6f, 0x64, - 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, - 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, - 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0xae, 0x04, 0x0a, 0x0e, 0x44, 0x6f, 0x74, 0x6e, 0x65, 0x74, + 0x65, 0x73, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x40, 0x0a, 0x1c, 0x75, 0x6e, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x65, 0x64, 0x5f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, + 0x5f, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x1a, 0x75, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x65, 0x64, 0x50, 0x61, 0x63, 0x6b, + 0x61, 0x67, 0x65, 0x44, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x22, 0x4a, 0x0a, 0x0c, 0x4e, + 0x6f, 0x64, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, + 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, + 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, + 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0xae, 0x04, 0x0a, 0x0e, 0x44, 0x6f, 0x74, 0x6e, + 0x65, 0x74, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, + 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, + 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, + 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x12, 0x5a, 0x0a, 0x10, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, + 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x6f, + 0x74, 0x6e, 0x65, 0x74, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x52, 0x65, 0x6e, + 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x52, 0x0f, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x73, 0x12, 0x5d, 0x0a, 0x11, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, 0x72, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x6f, 0x74, 0x6e, 0x65, + 0x74, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, + 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, + 0x10, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x73, 0x12, 0x2b, 0x0a, 0x11, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x10, 0x69, 0x67, + 0x6e, 0x6f, 0x72, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x12, 0x38, + 0x0a, 0x18, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x64, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, + 0x63, 0x65, 0x5f, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, + 0x52, 0x16, 0x66, 0x6f, 0x72, 0x63, 0x65, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, + 0x65, 0x41, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x16, 0x68, 0x61, 0x6e, 0x64, + 0x77, 0x72, 0x69, 0x74, 0x74, 0x65, 0x6e, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, + 0x65, 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x09, 0x52, 0x15, 0x68, 0x61, 0x6e, 0x64, 0x77, 0x72, + 0x69, 0x74, 0x74, 0x65, 0x6e, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x1a, + 0x42, 0x0a, 0x14, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, + 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, + 0x02, 0x38, 0x01, 0x1a, 0x43, 0x0a, 0x15, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x52, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, + 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, + 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x4a, 0x0a, 0x0c, 0x52, 0x75, 0x62, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x12, 0x5a, 0x0a, 0x10, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, - 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x6f, 0x74, 0x6e, - 0x65, 0x74, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x52, 0x65, 0x6e, 0x61, 0x6d, - 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, - 0x0f, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, - 0x12, 0x5d, 0x0a, 0x11, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x30, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x6f, 0x74, 0x6e, 0x65, 0x74, 0x53, - 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x52, - 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x10, 0x72, - 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x12, - 0x2b, 0x0a, 0x11, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x10, 0x69, 0x67, 0x6e, 0x6f, - 0x72, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, - 0x66, 0x6f, 0x72, 0x63, 0x65, 0x64, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, - 0x5f, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x16, - 0x66, 0x6f, 0x72, 0x63, 0x65, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x41, - 0x6c, 0x69, 0x61, 0x73, 0x65, 0x73, 0x12, 0x35, 0x0a, 0x16, 0x68, 0x61, 0x6e, 0x64, 0x77, 0x72, - 0x69, 0x74, 0x74, 0x65, 0x6e, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, - 0x18, 0x06, 0x20, 0x03, 0x28, 0x09, 0x52, 0x15, 0x68, 0x61, 0x6e, 0x64, 0x77, 0x72, 0x69, 0x74, - 0x74, 0x65, 0x6e, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x1a, 0x42, 0x0a, - 0x14, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, - 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, - 0x01, 0x1a, 0x43, 0x0a, 0x15, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x52, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, - 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x4a, 0x0a, 0x0c, 0x52, 0x75, 0x62, 0x79, 0x53, 0x65, - 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, - 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, - 0x6f, 0x6e, 0x22, 0xe4, 0x01, 0x0a, 0x0a, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, - 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, - 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x12, 0x56, 0x0a, - 0x10, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, - 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x45, - 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0f, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x73, 0x1a, 0x42, 0x0a, 0x14, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, - 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, - 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xc2, 0x03, 0x0a, 0x0e, 0x4d, 0x65, - 0x74, 0x68, 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x1a, 0x0a, 0x08, - 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, - 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x49, 0x0a, 0x0c, 0x6c, 0x6f, 0x6e, 0x67, - 0x5f, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4d, 0x65, 0x74, 0x68, - 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, 0x52, - 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x0b, 0x6c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, - 0x69, 0x6e, 0x67, 0x12, 0x32, 0x0a, 0x15, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x70, 0x6f, 0x70, 0x75, - 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, - 0x28, 0x09, 0x52, 0x13, 0x61, 0x75, 0x74, 0x6f, 0x50, 0x6f, 0x70, 0x75, 0x6c, 0x61, 0x74, 0x65, - 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x1a, 0x94, 0x02, 0x0a, 0x0b, 0x4c, 0x6f, 0x6e, 0x67, - 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x12, 0x47, 0x0a, 0x12, 0x69, 0x6e, 0x69, 0x74, 0x69, - 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, 0x01, 0x20, + 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0xe4, 0x01, 0x0a, 0x0a, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, + 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, + 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, + 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x12, + 0x56, 0x0a, 0x10, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, + 0x73, 0x2e, 0x52, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0f, 0x72, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x64, 0x53, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x1a, 0x42, 0x0a, 0x14, 0x52, 0x65, 0x6e, 0x61, 0x6d, + 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, + 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, + 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xc2, 0x03, 0x0a, 0x0e, + 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x1a, + 0x0a, 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x49, 0x0a, 0x0c, 0x6c, 0x6f, + 0x6e, 0x67, 0x5f, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x4c, 0x6f, 0x6e, + 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x0b, 0x6c, 0x6f, 0x6e, 0x67, 0x52, 0x75, + 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x12, 0x32, 0x0a, 0x15, 0x61, 0x75, 0x74, 0x6f, 0x5f, 0x70, 0x6f, + 0x70, 0x75, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x18, 0x03, + 0x20, 0x03, 0x28, 0x09, 0x52, 0x13, 0x61, 0x75, 0x74, 0x6f, 0x50, 0x6f, 0x70, 0x75, 0x6c, 0x61, + 0x74, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x1a, 0x94, 0x02, 0x0a, 0x0b, 0x4c, 0x6f, + 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x12, 0x47, 0x0a, 0x12, 0x69, 0x6e, 0x69, + 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x10, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, + 0x61, 0x79, 0x12, 0x32, 0x0a, 0x15, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, + 0x5f, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x02, 0x52, 0x13, 0x70, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x4d, 0x75, 0x6c, 0x74, + 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, + 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x50, 0x6f, + 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, 0x47, 0x0a, 0x12, 0x74, 0x6f, 0x74, 0x61, 0x6c, + 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, - 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, - 0x12, 0x32, 0x0a, 0x15, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x6d, - 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, - 0x13, 0x70, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, - 0x6c, 0x69, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, - 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, - 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x50, 0x6f, 0x6c, 0x6c, - 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, 0x47, 0x0a, 0x12, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x70, - 0x6f, 0x6c, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x74, 0x6f, - 0x74, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x22, 0x34, - 0x0a, 0x18, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x47, 0x61, 0x70, 0x69, 0x63, - 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, - 0x74, 0x68, 0x6f, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x74, - 0x68, 0x6f, 0x64, 0x73, 0x2a, 0xa3, 0x01, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, - 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x27, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x4c, 0x49, 0x42, - 0x52, 0x41, 0x52, 0x59, 0x5f, 0x4f, 0x52, 0x47, 0x41, 0x4e, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, - 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, - 0x09, 0x0a, 0x05, 0x43, 0x4c, 0x4f, 0x55, 0x44, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x44, - 0x53, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x50, 0x48, 0x4f, 0x54, 0x4f, 0x53, 0x10, 0x03, 0x12, - 0x0f, 0x0a, 0x0b, 0x53, 0x54, 0x52, 0x45, 0x45, 0x54, 0x5f, 0x56, 0x49, 0x45, 0x57, 0x10, 0x04, - 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x48, 0x4f, 0x50, 0x50, 0x49, 0x4e, 0x47, 0x10, 0x05, 0x12, 0x07, - 0x0a, 0x03, 0x47, 0x45, 0x4f, 0x10, 0x06, 0x12, 0x11, 0x0a, 0x0d, 0x47, 0x45, 0x4e, 0x45, 0x52, - 0x41, 0x54, 0x49, 0x56, 0x45, 0x5f, 0x41, 0x49, 0x10, 0x07, 0x2a, 0x67, 0x0a, 0x18, 0x43, 0x6c, - 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x44, 0x65, 0x73, 0x74, 0x69, - 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x26, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, - 0x5f, 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, 0x59, 0x5f, 0x44, 0x45, 0x53, 0x54, 0x49, 0x4e, 0x41, + 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, + 0x22, 0x75, 0x0a, 0x18, 0x53, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x47, 0x61, 0x70, + 0x69, 0x63, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, + 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x6d, + 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x12, 0x3f, 0x0a, 0x1c, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, + 0x74, 0x65, 0x5f, 0x6f, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x73, 0x5f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x19, 0x67, 0x65, + 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x4f, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x41, 0x73, 0x49, + 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2a, 0xa3, 0x01, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, + 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x27, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, + 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, 0x59, 0x5f, 0x4f, 0x52, 0x47, 0x41, 0x4e, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, - 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x47, 0x49, 0x54, 0x48, 0x55, 0x42, 0x10, 0x0a, 0x12, 0x13, - 0x0a, 0x0f, 0x50, 0x41, 0x43, 0x4b, 0x41, 0x47, 0x45, 0x5f, 0x4d, 0x41, 0x4e, 0x41, 0x47, 0x45, - 0x52, 0x10, 0x14, 0x3a, 0x4a, 0x0a, 0x10, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x73, 0x69, - 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, - 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9b, 0x08, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, - 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x3a, - 0x43, 0x0a, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x12, - 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x18, 0x99, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, - 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x43, 0x0a, 0x0c, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x73, 0x63, - 0x6f, 0x70, 0x65, 0x73, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9a, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6f, 0x61, - 0x75, 0x74, 0x68, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x3a, 0x44, 0x0a, 0x0b, 0x61, 0x70, 0x69, - 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xc1, 0xba, 0xab, 0xfa, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0a, 0x61, 0x70, 0x69, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x42, - 0x69, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, - 0x69, 0x42, 0x0b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, - 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, + 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x43, 0x4c, 0x4f, 0x55, 0x44, 0x10, 0x01, 0x12, 0x07, 0x0a, + 0x03, 0x41, 0x44, 0x53, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x50, 0x48, 0x4f, 0x54, 0x4f, 0x53, + 0x10, 0x03, 0x12, 0x0f, 0x0a, 0x0b, 0x53, 0x54, 0x52, 0x45, 0x45, 0x54, 0x5f, 0x56, 0x49, 0x45, + 0x57, 0x10, 0x04, 0x12, 0x0c, 0x0a, 0x08, 0x53, 0x48, 0x4f, 0x50, 0x50, 0x49, 0x4e, 0x47, 0x10, + 0x05, 0x12, 0x07, 0x0a, 0x03, 0x47, 0x45, 0x4f, 0x10, 0x06, 0x12, 0x11, 0x0a, 0x0d, 0x47, 0x45, + 0x4e, 0x45, 0x52, 0x41, 0x54, 0x49, 0x56, 0x45, 0x5f, 0x41, 0x49, 0x10, 0x07, 0x2a, 0x67, 0x0a, + 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x44, 0x65, + 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x26, 0x43, 0x4c, 0x49, + 0x45, 0x4e, 0x54, 0x5f, 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, 0x59, 0x5f, 0x44, 0x45, 0x53, 0x54, + 0x49, 0x4e, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, + 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x47, 0x49, 0x54, 0x48, 0x55, 0x42, 0x10, + 0x0a, 0x12, 0x13, 0x0a, 0x0f, 0x50, 0x41, 0x43, 0x4b, 0x41, 0x47, 0x45, 0x5f, 0x4d, 0x41, 0x4e, + 0x41, 0x47, 0x45, 0x52, 0x10, 0x14, 0x3a, 0x4a, 0x0a, 0x10, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, + 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9b, 0x08, 0x20, 0x03, 0x28, + 0x09, 0x52, 0x0f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, + 0x72, 0x65, 0x3a, 0x43, 0x0a, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, 0x6f, + 0x73, 0x74, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x18, 0x99, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x43, 0x0a, 0x0c, 0x6f, 0x61, 0x75, 0x74, 0x68, + 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9a, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0b, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x3a, 0x44, 0x0a, 0x0b, + 0x61, 0x70, 0x69, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0xc1, 0xba, 0xab, + 0xfa, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x61, 0x70, 0x69, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x42, 0x69, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x61, 0x70, 0x69, 0x42, 0x0b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, + 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, + 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go index ffb5838cb..c93b4f524 100644 --- a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go +++ b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go @@ -663,14 +663,14 @@ var file_google_api_http_proto_rawDesc = []byte{ 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x42, 0x6a, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, + 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x42, 0x67, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, 0x09, 0x48, 0x74, 0x74, 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x04, - 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, + 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go index b5db279ae..a1c543a94 100644 --- a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go +++ b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go @@ -556,15 +556,14 @@ var file_google_api_resource_proto_rawDesc = []byte{ 0x67, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9d, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, - 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x6e, 0x0a, 0x0e, 0x63, 0x6f, + 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x42, 0x6b, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, + 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go index 1d8397b02..2b54db304 100644 --- a/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go +++ b/e2e/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go @@ -69,7 +69,7 @@ const ( // The routing header consists of one or multiple key-value pairs. Every key // and value must be percent-encoded, and joined together in the format of // `key1=value1&key2=value2`. -// In the examples below I am skipping the percent-encoding for readablity. +// The examples below skip the percent-encoding for readability. // // # Example 1 // diff --git a/e2e/vendor/google.golang.org/grpc/balancer/base/balancer.go b/e2e/vendor/google.golang.org/grpc/balancer/base/balancer.go index d5ed172ae..4d576876d 100644 --- a/e2e/vendor/google.golang.org/grpc/balancer/base/balancer.go +++ b/e2e/vendor/google.golang.org/grpc/balancer/base/balancer.go @@ -41,7 +41,7 @@ func (bb *baseBuilder) Build(cc balancer.ClientConn, _ balancer.BuildOptions) ba cc: cc, pickerBuilder: bb.pickerBuilder, - subConns: resolver.NewAddressMap(), + subConns: resolver.NewAddressMapV2[balancer.SubConn](), scStates: make(map[balancer.SubConn]connectivity.State), csEvltr: &balancer.ConnectivityStateEvaluator{}, config: bb.config, @@ -65,7 +65,7 @@ type baseBalancer struct { csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State - subConns *resolver.AddressMap + subConns *resolver.AddressMapV2[balancer.SubConn] scStates map[balancer.SubConn]connectivity.State picker balancer.Picker config Config @@ -100,7 +100,7 @@ func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { // Successful resolution; clear resolver error and ensure we return nil. b.resolverErr = nil // addrsSet is the set converted from addrs, it's used for quick lookup of an address. - addrsSet := resolver.NewAddressMap() + addrsSet := resolver.NewAddressMapV2[any]() for _, a := range s.ResolverState.Addresses { addrsSet.Set(a, nil) if _, ok := b.subConns.Get(a); !ok { @@ -122,8 +122,7 @@ func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { } } for _, a := range b.subConns.Keys() { - sci, _ := b.subConns.Get(a) - sc := sci.(balancer.SubConn) + sc, _ := b.subConns.Get(a) // a was removed by resolver. if _, ok := addrsSet.Get(a); !ok { sc.Shutdown() @@ -173,8 +172,7 @@ func (b *baseBalancer) regeneratePicker() { // Filter out all ready SCs from full subConn map. for _, addr := range b.subConns.Keys() { - sci, _ := b.subConns.Get(addr) - sc := sci.(balancer.SubConn) + sc, _ := b.subConns.Get(addr) if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { readySCs[sc] = SubConnInfo{Address: addr} } diff --git a/e2e/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go b/e2e/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go index 421c4fecc..cc606f4da 100644 --- a/e2e/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go +++ b/e2e/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go @@ -73,7 +73,7 @@ func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions, childBuilde esOpts: esOpts, childBuilder: childBuilder, } - es.children.Store(resolver.NewEndpointMap()) + es.children.Store(resolver.NewEndpointMap[*balancerWrapper]()) return es } @@ -90,7 +90,7 @@ type endpointSharding struct { // calls into a child. To avoid deadlocks, do not acquire childMu while // holding mu. childMu sync.Mutex - children atomic.Pointer[resolver.EndpointMap] // endpoint -> *balancerWrapper + children atomic.Pointer[resolver.EndpointMap[*balancerWrapper]] // inhibitChildUpdates is set during UpdateClientConnState/ResolverError // calls (calls to children will each produce an update, only want one @@ -122,7 +122,7 @@ func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState var ret error children := es.children.Load() - newChildren := resolver.NewEndpointMap() + newChildren := resolver.NewEndpointMap[*balancerWrapper]() // Update/Create new children. for _, endpoint := range state.ResolverState.Endpoints { @@ -131,9 +131,8 @@ func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState // update. continue } - var childBalancer *balancerWrapper - if val, ok := children.Get(endpoint); ok { - childBalancer = val.(*balancerWrapper) + childBalancer, ok := children.Get(endpoint) + if ok { // Endpoint attributes may have changed, update the stored endpoint. es.mu.Lock() childBalancer.childState.Endpoint = endpoint @@ -166,7 +165,7 @@ func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState for _, e := range children.Keys() { child, _ := children.Get(e) if _, ok := newChildren.Get(e); !ok { - child.(*balancerWrapper).closeLocked() + child.closeLocked() } } es.children.Store(newChildren) @@ -189,7 +188,7 @@ func (es *endpointSharding) ResolverError(err error) { }() children := es.children.Load() for _, child := range children.Values() { - child.(*balancerWrapper).resolverErrorLocked(err) + child.resolverErrorLocked(err) } } @@ -202,7 +201,7 @@ func (es *endpointSharding) Close() { defer es.childMu.Unlock() children := es.children.Load() for _, child := range children.Values() { - child.(*balancerWrapper).closeLocked() + child.closeLocked() } } @@ -222,8 +221,7 @@ func (es *endpointSharding) updateState() { childStates := make([]ChildState, 0, children.Len()) for _, child := range children.Values() { - bw := child.(*balancerWrapper) - childState := bw.childState + childState := child.childState childStates = append(childStates, childState) childPicker := childState.State.Picker switch childState.State.ConnectivityState { diff --git a/e2e/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go b/e2e/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go index 113181e6b..494314f23 100644 --- a/e2e/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go +++ b/e2e/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirstleaf/pickfirstleaf.go @@ -122,7 +122,7 @@ func (pickfirstBuilder) Build(cc balancer.ClientConn, bo balancer.BuildOptions) target: bo.Target.String(), metricsRecorder: cc.MetricsRecorder(), - subConns: resolver.NewAddressMap(), + subConns: resolver.NewAddressMapV2[*scData](), state: connectivity.Connecting, cancelConnectionTimer: func() {}, } @@ -220,7 +220,7 @@ type pickfirstBalancer struct { // updates. state connectivity.State // scData for active subonns mapped by address. - subConns *resolver.AddressMap + subConns *resolver.AddressMapV2[*scData] addressList addressList firstPass bool numTF int @@ -319,7 +319,7 @@ func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState prevAddr := b.addressList.currentAddress() prevSCData, found := b.subConns.Get(prevAddr) prevAddrsCount := b.addressList.size() - isPrevRawConnectivityStateReady := found && prevSCData.(*scData).rawConnectivityState == connectivity.Ready + isPrevRawConnectivityStateReady := found && prevSCData.rawConnectivityState == connectivity.Ready b.addressList.updateAddrs(newAddrs) // If the previous ready SubConn exists in new address list, @@ -381,21 +381,21 @@ func (b *pickfirstBalancer) startFirstPassLocked() { b.numTF = 0 // Reset the connection attempt record for existing SubConns. for _, sd := range b.subConns.Values() { - sd.(*scData).connectionFailedInFirstPass = false + sd.connectionFailedInFirstPass = false } b.requestConnectionLocked() } func (b *pickfirstBalancer) closeSubConnsLocked() { for _, sd := range b.subConns.Values() { - sd.(*scData).subConn.Shutdown() + sd.subConn.Shutdown() } - b.subConns = resolver.NewAddressMap() + b.subConns = resolver.NewAddressMapV2[*scData]() } // deDupAddresses ensures that each address appears only once in the slice. func deDupAddresses(addrs []resolver.Address) []resolver.Address { - seenAddrs := resolver.NewAddressMap() + seenAddrs := resolver.NewAddressMapV2[*scData]() retAddrs := []resolver.Address{} for _, addr := range addrs { @@ -481,7 +481,7 @@ func addressFamily(address string) ipAddrFamily { // This ensures that the subchannel map accurately reflects the current set of // addresses received from the name resolver. func (b *pickfirstBalancer) reconcileSubConnsLocked(newAddrs []resolver.Address) { - newAddrsMap := resolver.NewAddressMap() + newAddrsMap := resolver.NewAddressMapV2[bool]() for _, addr := range newAddrs { newAddrsMap.Set(addr, true) } @@ -491,7 +491,7 @@ func (b *pickfirstBalancer) reconcileSubConnsLocked(newAddrs []resolver.Address) continue } val, _ := b.subConns.Get(oldAddr) - val.(*scData).subConn.Shutdown() + val.subConn.Shutdown() b.subConns.Delete(oldAddr) } } @@ -500,13 +500,12 @@ func (b *pickfirstBalancer) reconcileSubConnsLocked(newAddrs []resolver.Address) // becomes ready, which means that all other subConn must be shutdown. func (b *pickfirstBalancer) shutdownRemainingLocked(selected *scData) { b.cancelConnectionTimer() - for _, v := range b.subConns.Values() { - sd := v.(*scData) + for _, sd := range b.subConns.Values() { if sd.subConn != selected.subConn { sd.subConn.Shutdown() } } - b.subConns = resolver.NewAddressMap() + b.subConns = resolver.NewAddressMapV2[*scData]() b.subConns.Set(selected.addr, selected) } @@ -539,18 +538,17 @@ func (b *pickfirstBalancer) requestConnectionLocked() { b.subConns.Set(curAddr, sd) } - scd := sd.(*scData) - switch scd.rawConnectivityState { + switch sd.rawConnectivityState { case connectivity.Idle: - scd.subConn.Connect() + sd.subConn.Connect() b.scheduleNextConnectionLocked() return case connectivity.TransientFailure: // The SubConn is being re-used and failed during a previous pass // over the addressList. It has not completed backoff yet. // Mark it as having failed and try the next address. - scd.connectionFailedInFirstPass = true - lastErr = scd.lastErr + sd.connectionFailedInFirstPass = true + lastErr = sd.lastErr continue case connectivity.Connecting: // Wait for the connection attempt to complete or the timer to fire @@ -558,7 +556,7 @@ func (b *pickfirstBalancer) requestConnectionLocked() { b.scheduleNextConnectionLocked() return default: - b.logger.Errorf("SubConn with unexpected state %v present in SubConns map.", scd.rawConnectivityState) + b.logger.Errorf("SubConn with unexpected state %v present in SubConns map.", sd.rawConnectivityState) return } @@ -753,8 +751,7 @@ func (b *pickfirstBalancer) endFirstPassIfPossibleLocked(lastErr error) { } // Connect() has been called on all the SubConns. The first pass can be // ended if all the SubConns have reported a failure. - for _, v := range b.subConns.Values() { - sd := v.(*scData) + for _, sd := range b.subConns.Values() { if !sd.connectionFailedInFirstPass { return } @@ -765,8 +762,7 @@ func (b *pickfirstBalancer) endFirstPassIfPossibleLocked(lastErr error) { Picker: &picker{err: lastErr}, }) // Start re-connecting all the SubConns that are already in IDLE. - for _, v := range b.subConns.Values() { - sd := v.(*scData) + for _, sd := range b.subConns.Values() { if sd.rawConnectivityState == connectivity.Idle { sd.subConn.Connect() } @@ -927,6 +923,5 @@ func (al *addressList) hasNext() bool { // fields that are meaningful to the SubConn. func equalAddressIgnoringBalAttributes(a, b *resolver.Address) bool { return a.Addr == b.Addr && a.ServerName == b.ServerName && - a.Attributes.Equal(b.Attributes) && - a.Metadata == b.Metadata + a.Attributes.Equal(b.Attributes) } diff --git a/e2e/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/e2e/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index b2f8fc7f4..825c31795 100644 --- a/e2e/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/e2e/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -18,7 +18,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.4 +// protoc-gen-go v1.36.5 // protoc v5.27.1 // source: grpc/binlog/v1/binarylog.proto diff --git a/e2e/vendor/google.golang.org/grpc/clientconn.go b/e2e/vendor/google.golang.org/grpc/clientconn.go index a319ef979..4f350ca56 100644 --- a/e2e/vendor/google.golang.org/grpc/clientconn.go +++ b/e2e/vendor/google.golang.org/grpc/clientconn.go @@ -1231,8 +1231,7 @@ func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error) // adjustParams updates parameters used to create transports upon // receiving a GoAway. func (ac *addrConn) adjustParams(r transport.GoAwayReason) { - switch r { - case transport.GoAwayTooManyPings: + if r == transport.GoAwayTooManyPings { v := 2 * ac.dopts.copts.KeepaliveParams.Time ac.cc.mu.Lock() if v > ac.cc.keepaliveParams.Time { diff --git a/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go index 94177b05c..faa59e418 100644 --- a/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ b/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go @@ -17,7 +17,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.4 +// protoc-gen-go v1.36.5 // protoc v5.27.1 // source: grpc/health/v1/health.proto @@ -178,6 +178,87 @@ func (x *HealthCheckResponse) GetStatus() HealthCheckResponse_ServingStatus { return HealthCheckResponse_UNKNOWN } +type HealthListRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *HealthListRequest) Reset() { + *x = HealthListRequest{} + mi := &file_grpc_health_v1_health_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *HealthListRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HealthListRequest) ProtoMessage() {} + +func (x *HealthListRequest) ProtoReflect() protoreflect.Message { + mi := &file_grpc_health_v1_health_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HealthListRequest.ProtoReflect.Descriptor instead. +func (*HealthListRequest) Descriptor() ([]byte, []int) { + return file_grpc_health_v1_health_proto_rawDescGZIP(), []int{2} +} + +type HealthListResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // statuses contains all the services and their respective status. + Statuses map[string]*HealthCheckResponse `protobuf:"bytes,1,rep,name=statuses,proto3" json:"statuses,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *HealthListResponse) Reset() { + *x = HealthListResponse{} + mi := &file_grpc_health_v1_health_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *HealthListResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HealthListResponse) ProtoMessage() {} + +func (x *HealthListResponse) ProtoReflect() protoreflect.Message { + mi := &file_grpc_health_v1_health_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HealthListResponse.ProtoReflect.Descriptor instead. +func (*HealthListResponse) Descriptor() ([]byte, []int) { + return file_grpc_health_v1_health_proto_rawDescGZIP(), []int{3} +} + +func (x *HealthListResponse) GetStatuses() map[string]*HealthCheckResponse { + if x != nil { + return x.Statuses + } + return nil +} + var File_grpc_health_v1_health_proto protoreflect.FileDescriptor var file_grpc_health_v1_health_proto_rawDesc = string([]byte{ @@ -198,25 +279,44 @@ var file_grpc_health_v1_health_proto_rawDesc = string([]byte{ 0x0a, 0x07, 0x53, 0x45, 0x52, 0x56, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4e, 0x4f, 0x54, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x5f, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, - 0x03, 0x32, 0xae, 0x01, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x50, 0x0a, 0x05, - 0x43, 0x68, 0x65, 0x63, 0x6b, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, + 0x03, 0x22, 0x13, 0x0a, 0x11, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0xc4, 0x01, 0x0a, 0x12, 0x48, 0x65, 0x61, 0x6c, 0x74, + 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4c, 0x0a, + 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x30, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, + 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x52, 0x08, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x1a, 0x60, 0x0a, 0x0d, 0x53, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, + 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x39, + 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x23, 0x2e, + 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, + 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x32, 0xfd, 0x01, + 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x50, 0x0a, 0x05, 0x43, 0x68, 0x65, 0x63, + 0x6b, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, + 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, - 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, 0x70, 0x63, - 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x52, - 0x0a, 0x05, 0x57, 0x61, 0x74, 0x63, 0x68, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, - 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, - 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, - 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x30, 0x01, 0x42, 0x70, 0x0a, 0x11, 0x69, 0x6f, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, - 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, - 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x68, - 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x5f, 0x76, 0x31, 0xa2, 0x02, 0x0c, 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x56, 0x31, 0xaa, 0x02, 0x0e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, - 0x68, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4d, 0x0a, 0x04, 0x4c, 0x69, + 0x73, 0x74, 0x12, 0x21, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x4c, 0x69, 0x73, + 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x52, 0x0a, 0x05, 0x57, 0x61, 0x74, + 0x63, 0x68, 0x12, 0x22, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, + 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x43, 0x68, + 0x65, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x30, 0x01, 0x42, 0x70, 0x0a, + 0x11, 0x69, 0x6f, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, + 0x76, 0x31, 0x42, 0x0b, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x2c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, + 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, + 0x2f, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x68, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x5f, 0x76, 0x31, 0xa2, + 0x02, 0x0c, 0x47, 0x72, 0x70, 0x63, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x56, 0x31, 0xaa, 0x02, + 0x0e, 0x47, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x2e, 0x56, 0x31, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, }) var ( @@ -232,23 +332,30 @@ func file_grpc_health_v1_health_proto_rawDescGZIP() []byte { } var file_grpc_health_v1_health_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_grpc_health_v1_health_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_grpc_health_v1_health_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_grpc_health_v1_health_proto_goTypes = []any{ (HealthCheckResponse_ServingStatus)(0), // 0: grpc.health.v1.HealthCheckResponse.ServingStatus (*HealthCheckRequest)(nil), // 1: grpc.health.v1.HealthCheckRequest (*HealthCheckResponse)(nil), // 2: grpc.health.v1.HealthCheckResponse + (*HealthListRequest)(nil), // 3: grpc.health.v1.HealthListRequest + (*HealthListResponse)(nil), // 4: grpc.health.v1.HealthListResponse + nil, // 5: grpc.health.v1.HealthListResponse.StatusesEntry } var file_grpc_health_v1_health_proto_depIdxs = []int32{ 0, // 0: grpc.health.v1.HealthCheckResponse.status:type_name -> grpc.health.v1.HealthCheckResponse.ServingStatus - 1, // 1: grpc.health.v1.Health.Check:input_type -> grpc.health.v1.HealthCheckRequest - 1, // 2: grpc.health.v1.Health.Watch:input_type -> grpc.health.v1.HealthCheckRequest - 2, // 3: grpc.health.v1.Health.Check:output_type -> grpc.health.v1.HealthCheckResponse - 2, // 4: grpc.health.v1.Health.Watch:output_type -> grpc.health.v1.HealthCheckResponse - 3, // [3:5] is the sub-list for method output_type - 1, // [1:3] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name + 5, // 1: grpc.health.v1.HealthListResponse.statuses:type_name -> grpc.health.v1.HealthListResponse.StatusesEntry + 2, // 2: grpc.health.v1.HealthListResponse.StatusesEntry.value:type_name -> grpc.health.v1.HealthCheckResponse + 1, // 3: grpc.health.v1.Health.Check:input_type -> grpc.health.v1.HealthCheckRequest + 3, // 4: grpc.health.v1.Health.List:input_type -> grpc.health.v1.HealthListRequest + 1, // 5: grpc.health.v1.Health.Watch:input_type -> grpc.health.v1.HealthCheckRequest + 2, // 6: grpc.health.v1.Health.Check:output_type -> grpc.health.v1.HealthCheckResponse + 4, // 7: grpc.health.v1.Health.List:output_type -> grpc.health.v1.HealthListResponse + 2, // 8: grpc.health.v1.Health.Watch:output_type -> grpc.health.v1.HealthCheckResponse + 6, // [6:9] is the sub-list for method output_type + 3, // [3:6] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name } func init() { file_grpc_health_v1_health_proto_init() } @@ -262,7 +369,7 @@ func file_grpc_health_v1_health_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_grpc_health_v1_health_proto_rawDesc), len(file_grpc_health_v1_health_proto_rawDesc)), NumEnums: 1, - NumMessages: 2, + NumMessages: 5, NumExtensions: 0, NumServices: 1, }, diff --git a/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go index f96b8ab49..93136610e 100644 --- a/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ b/e2e/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -37,6 +37,7 @@ const _ = grpc.SupportPackageIsVersion9 const ( Health_Check_FullMethodName = "/grpc.health.v1.Health/Check" + Health_List_FullMethodName = "/grpc.health.v1.Health/List" Health_Watch_FullMethodName = "/grpc.health.v1.Health/Watch" ) @@ -55,9 +56,19 @@ type HealthClient interface { // // Clients should set a deadline when calling Check, and can declare the // server unhealthy if they do not receive a timely response. - // - // Check implementations should be idempotent and side effect free. Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) + // List provides a non-atomic snapshot of the health of all the available + // services. + // + // The server may respond with a RESOURCE_EXHAUSTED error if too many services + // exist. + // + // Clients should set a deadline when calling List, and can declare the server + // unhealthy if they do not receive a timely response. + // + // Clients should keep in mind that the list of health services exposed by an + // application can change over the lifetime of the process. + List(ctx context.Context, in *HealthListRequest, opts ...grpc.CallOption) (*HealthListResponse, error) // Performs a watch for the serving status of the requested service. // The server will immediately send back a message indicating the current // serving status. It will then subsequently send a new message whenever @@ -94,6 +105,16 @@ func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts . return out, nil } +func (c *healthClient) List(ctx context.Context, in *HealthListRequest, opts ...grpc.CallOption) (*HealthListResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(HealthListResponse) + err := c.cc.Invoke(ctx, Health_List_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[HealthCheckResponse], error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) stream, err := c.cc.NewStream(ctx, &Health_ServiceDesc.Streams[0], Health_Watch_FullMethodName, cOpts...) @@ -128,9 +149,19 @@ type HealthServer interface { // // Clients should set a deadline when calling Check, and can declare the // server unhealthy if they do not receive a timely response. - // - // Check implementations should be idempotent and side effect free. Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) + // List provides a non-atomic snapshot of the health of all the available + // services. + // + // The server may respond with a RESOURCE_EXHAUSTED error if too many services + // exist. + // + // Clients should set a deadline when calling List, and can declare the server + // unhealthy if they do not receive a timely response. + // + // Clients should keep in mind that the list of health services exposed by an + // application can change over the lifetime of the process. + List(context.Context, *HealthListRequest) (*HealthListResponse, error) // Performs a watch for the serving status of the requested service. // The server will immediately send back a message indicating the current // serving status. It will then subsequently send a new message whenever @@ -159,6 +190,9 @@ type UnimplementedHealthServer struct{} func (UnimplementedHealthServer) Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") } +func (UnimplementedHealthServer) List(context.Context, *HealthListRequest) (*HealthListResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method List not implemented") +} func (UnimplementedHealthServer) Watch(*HealthCheckRequest, grpc.ServerStreamingServer[HealthCheckResponse]) error { return status.Errorf(codes.Unimplemented, "method Watch not implemented") } @@ -200,6 +234,24 @@ func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interf return interceptor(ctx, in, info, handler) } +func _Health_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(HealthListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(HealthServer).List(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Health_List_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(HealthServer).List(ctx, req.(*HealthListRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { m := new(HealthCheckRequest) if err := stream.RecvMsg(m); err != nil { @@ -222,6 +274,10 @@ var Health_ServiceDesc = grpc.ServiceDesc{ MethodName: "Check", Handler: _Health_Check_Handler, }, + { + MethodName: "List", + Handler: _Health_List_Handler, + }, }, Streams: []grpc.StreamDesc{ { diff --git a/e2e/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/e2e/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 1e42b6fdc..cc5713fd9 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/e2e/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -51,10 +51,24 @@ var ( // xDS server in the list of server configs will be used. XDSFallbackSupport = boolFromEnv("GRPC_EXPERIMENTAL_XDS_FALLBACK", true) // NewPickFirstEnabled is set if the new pickfirst leaf policy is to be used - // instead of the exiting pickfirst implementation. This can be enabled by + // instead of the exiting pickfirst implementation. This can be disabled by // setting the environment variable "GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST" - // to "true". - NewPickFirstEnabled = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST", false) + // to "false". + NewPickFirstEnabled = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_NEW_PICK_FIRST", true) + + // XDSEndpointHashKeyBackwardCompat controls the parsing of the endpoint hash + // key from EDS LbEndpoint metadata. Endpoint hash keys can be disabled by + // setting "GRPC_XDS_ENDPOINT_HASH_KEY_BACKWARD_COMPAT" to "true". When the + // implementation of A76 is stable, we will flip the default value to false + // in a subsequent release. A final release will remove this environment + // variable, enabling the new behavior unconditionally. + XDSEndpointHashKeyBackwardCompat = boolFromEnv("GRPC_XDS_ENDPOINT_HASH_KEY_BACKWARD_COMPAT", true) + + // RingHashSetRequestHashKey is set if the ring hash balancer can get the + // request hash header by setting the "requestHashHeader" field, according + // to gRFC A76. It can be enabled by setting the environment variable + // "GRPC_EXPERIMENTAL_RING_HASH_SET_REQUEST_HASH_KEY" to "true". + RingHashSetRequestHashKey = boolFromEnv("GRPC_EXPERIMENTAL_RING_HASH_SET_REQUEST_HASH_KEY", false) ) func boolFromEnv(envVar string, def bool) bool { diff --git a/e2e/vendor/google.golang.org/grpc/internal/internal.go b/e2e/vendor/google.golang.org/grpc/internal/internal.go index 13e1f386b..2ce012cda 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/internal.go +++ b/e2e/vendor/google.golang.org/grpc/internal/internal.go @@ -259,6 +259,13 @@ var ( // SetBufferPoolingThresholdForTesting updates the buffer pooling threshold, for // testing purposes. SetBufferPoolingThresholdForTesting any // func(int) + + // TimeAfterFunc is used to create timers. During tests the function is + // replaced to track allocated timers and fail the test if a timer isn't + // cancelled. + TimeAfterFunc = func(d time.Duration, f func()) Timer { + return time.AfterFunc(d, f) + } ) // HealthChecker defines the signature of the client-side LB channel health @@ -300,3 +307,9 @@ type EnforceSubConnEmbedding interface { type EnforceClientConnEmbedding interface { enforceClientConnEmbedding() } + +// Timer is an interface to allow injecting different time.Timer implementations +// during tests. +type Timer interface { + Stop() bool +} diff --git a/e2e/vendor/google.golang.org/grpc/internal/metadata/metadata.go b/e2e/vendor/google.golang.org/grpc/internal/metadata/metadata.go index 900bfb716..c4055bc00 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/metadata/metadata.go +++ b/e2e/vendor/google.golang.org/grpc/internal/metadata/metadata.go @@ -97,13 +97,11 @@ func hasNotPrintable(msg string) bool { return false } -// ValidatePair validate a key-value pair with the following rules (the pseudo-header will be skipped) : -// -// - key must contain one or more characters. -// - the characters in the key must be contained in [0-9 a-z _ - .]. -// - if the key ends with a "-bin" suffix, no validation of the corresponding value is performed. -// - the characters in the every value must be printable (in [%x20-%x7E]). -func ValidatePair(key string, vals ...string) error { +// ValidateKey validates a key with the following rules (pseudo-headers are +// skipped): +// - the key must contain one or more characters. +// - the characters in the key must be in [0-9 a-z _ - .]. +func ValidateKey(key string) error { // key should not be empty if key == "" { return fmt.Errorf("there is an empty key in the header") @@ -119,6 +117,20 @@ func ValidatePair(key string, vals ...string) error { return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", key) } } + return nil +} + +// ValidatePair validates a key-value pair with the following rules +// (pseudo-header are skipped): +// - the key must contain one or more characters. +// - the characters in the key must be in [0-9 a-z _ - .]. +// - if the key ends with a "-bin" suffix, no validation of the corresponding +// value is performed. +// - the characters in every value must be printable (in [%x20-%x7E]). +func ValidatePair(key string, vals ...string) error { + if err := ValidateKey(key); err != nil { + return err + } if strings.HasSuffix(key, "-bin") { return nil } diff --git a/e2e/vendor/google.golang.org/grpc/internal/transport/client_stream.go b/e2e/vendor/google.golang.org/grpc/internal/transport/client_stream.go index 8ed347c54..ccc0e017e 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/transport/client_stream.go +++ b/e2e/vendor/google.golang.org/grpc/internal/transport/client_stream.go @@ -59,7 +59,7 @@ func (s *ClientStream) Read(n int) (mem.BufferSlice, error) { return b, err } -// Close closes the stream and popagates err to any readers. +// Close closes the stream and propagates err to any readers. func (s *ClientStream) Close(err error) { var ( rst bool diff --git a/e2e/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/e2e/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 513dbb93d..ae9316662 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/e2e/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -1390,8 +1390,7 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) error { // the caller. func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { t.goAwayReason = GoAwayNoReason - switch f.ErrCode { - case http2.ErrCodeEnhanceYourCalm: + if f.ErrCode == http2.ErrCodeEnhanceYourCalm { if string(f.DebugData()) == "too_many_pings" { t.goAwayReason = GoAwayTooManyPings } diff --git a/e2e/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/e2e/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 997b0a59b..7e53eb173 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/e2e/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -35,6 +35,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/pretty" @@ -598,6 +599,22 @@ func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeade if len(t.activeStreams) == 1 { t.idle = time.Time{} } + // Start a timer to close the stream on reaching the deadline. + if timeoutSet { + // We need to wait for s.cancel to be updated before calling + // t.closeStream to avoid data races. + cancelUpdated := make(chan struct{}) + timer := internal.TimeAfterFunc(timeout, func() { + <-cancelUpdated + t.closeStream(s, true, http2.ErrCodeCancel, false) + }) + oldCancel := s.cancel + s.cancel = func() { + oldCancel() + timer.Stop() + } + close(cancelUpdated) + } t.mu.Unlock() if channelz.IsOn() { t.channelz.SocketMetrics.StreamsStarted.Add(1) @@ -1274,7 +1291,6 @@ func (t *http2Server) Close(err error) { // deleteStream deletes the stream s from transport's active streams. func (t *http2Server) deleteStream(s *ServerStream, eosReceived bool) { - t.mu.Lock() if _, ok := t.activeStreams[s.id]; ok { delete(t.activeStreams, s.id) @@ -1324,7 +1340,10 @@ func (t *http2Server) closeStream(s *ServerStream, rst bool, rstCode http2.ErrCo // called to interrupt the potential blocking on other goroutines. s.cancel() - s.swapState(streamDone) + oldState := s.swapState(streamDone) + if oldState == streamDone { + return + } t.deleteStream(s, eosReceived) t.controlBuf.put(&cleanupStream{ diff --git a/e2e/vendor/google.golang.org/grpc/internal/transport/server_stream.go b/e2e/vendor/google.golang.org/grpc/internal/transport/server_stream.go index a22a90151..cf8da0b52 100644 --- a/e2e/vendor/google.golang.org/grpc/internal/transport/server_stream.go +++ b/e2e/vendor/google.golang.org/grpc/internal/transport/server_stream.go @@ -35,8 +35,10 @@ type ServerStream struct { *Stream // Embed for common stream functionality. st internalServerTransport - ctxDone <-chan struct{} // closed at the end of stream. Cache of ctx.Done() (for performance) - cancel context.CancelFunc // invoked at the end of stream to cancel ctx. + ctxDone <-chan struct{} // closed at the end of stream. Cache of ctx.Done() (for performance) + // cancel is invoked at the end of stream to cancel ctx. It also stops the + // timer for monitoring the rpc deadline if configured. + cancel func() // Holds compressor names passed in grpc-accept-encoding metadata from the // client. diff --git a/e2e/vendor/google.golang.org/grpc/resolver/manual/manual.go b/e2e/vendor/google.golang.org/grpc/resolver/manual/manual.go index 09e864a89..82fcc2e35 100644 --- a/e2e/vendor/google.golang.org/grpc/resolver/manual/manual.go +++ b/e2e/vendor/google.golang.org/grpc/resolver/manual/manual.go @@ -62,7 +62,7 @@ type Resolver struct { // Fields actually belong to the resolver. // Guards access to below fields. mu sync.Mutex - CC resolver.ClientConn + cc resolver.ClientConn // Storing the most recent state update makes this resolver resilient to // restarts, which is possible with channel idleness. lastSeenState *resolver.State @@ -78,12 +78,12 @@ func (r *Resolver) InitialState(s resolver.State) { func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { r.mu.Lock() defer r.mu.Unlock() - // Call BuildCallback after locking to avoid a race when UpdateState - // or ReportError is called before Build returns. + // Call BuildCallback after locking to avoid a race when UpdateState or CC + // is called before Build returns. r.BuildCallback(target, cc, opts) - r.CC = cc + r.cc = cc if r.lastSeenState != nil { - err := r.CC.UpdateState(*r.lastSeenState) + err := r.cc.UpdateState(*r.lastSeenState) go r.UpdateStateCallback(err) } return r, nil @@ -104,25 +104,27 @@ func (r *Resolver) Close() { r.CloseCallback() } -// UpdateState calls CC.UpdateState. +// UpdateState calls UpdateState(s) on the channel. If the resolver has not +// been Built before, this instead sets the initial state of the resolver, like +// InitialState. func (r *Resolver) UpdateState(s resolver.State) { r.mu.Lock() defer r.mu.Unlock() - var err error - if r.CC == nil { - panic("cannot update state as grpc.Dial with resolver has not been called") - } - err = r.CC.UpdateState(s) r.lastSeenState = &s + if r.cc == nil { + return + } + err := r.cc.UpdateState(s) r.UpdateStateCallback(err) } -// ReportError calls CC.ReportError. -func (r *Resolver) ReportError(err error) { +// CC returns r's ClientConn when r was last Built. Panics if the resolver has +// not been Built before. +func (r *Resolver) CC() resolver.ClientConn { r.mu.Lock() defer r.mu.Unlock() - if r.CC == nil { - panic("cannot report error as grpc.Dial with resolver has not been called") + if r.cc == nil { + panic("Manual resolver instance has not yet been built.") } - r.CC.ReportError(err) + return r.cc } diff --git a/e2e/vendor/google.golang.org/grpc/resolver/map.go b/e2e/vendor/google.golang.org/grpc/resolver/map.go index 975b49970..c3c15ac96 100644 --- a/e2e/vendor/google.golang.org/grpc/resolver/map.go +++ b/e2e/vendor/google.golang.org/grpc/resolver/map.go @@ -24,16 +24,22 @@ import ( "strings" ) -type addressMapEntry struct { +type addressMapEntry[T any] struct { addr Address - value any + value T } -// AddressMap is a map of addresses to arbitrary values taking into account +// AddressMap is an AddressMapV2[any]. It will be deleted in an upcoming +// release of grpc-go. +// +// Deprecated: use the generic AddressMapV2 type instead. +type AddressMap = AddressMapV2[any] + +// AddressMapV2 is a map of addresses to arbitrary values taking into account // Attributes. BalancerAttributes are ignored, as are Metadata and Type. // Multiple accesses may not be performed concurrently. Must be created via // NewAddressMap; do not construct directly. -type AddressMap struct { +type AddressMapV2[T any] struct { // The underlying map is keyed by an Address with fields that we don't care // about being set to their zero values. The only fields that we care about // are `Addr`, `ServerName` and `Attributes`. Since we need to be able to @@ -47,23 +53,30 @@ type AddressMap struct { // The value type of the map contains a slice of addresses which match the key // in their `Addr` and `ServerName` fields and contain the corresponding value // associated with them. - m map[Address]addressMapEntryList + m map[Address]addressMapEntryList[T] } func toMapKey(addr *Address) Address { return Address{Addr: addr.Addr, ServerName: addr.ServerName} } -type addressMapEntryList []*addressMapEntry +type addressMapEntryList[T any] []*addressMapEntry[T] -// NewAddressMap creates a new AddressMap. +// NewAddressMap creates a new AddressMapV2[any]. +// +// Deprecated: use the generic NewAddressMapV2 constructor instead. func NewAddressMap() *AddressMap { - return &AddressMap{m: make(map[Address]addressMapEntryList)} + return NewAddressMapV2[any]() +} + +// NewAddressMapV2 creates a new AddressMapV2. +func NewAddressMapV2[T any]() *AddressMapV2[T] { + return &AddressMapV2[T]{m: make(map[Address]addressMapEntryList[T])} } // find returns the index of addr in the addressMapEntry slice, or -1 if not // present. -func (l addressMapEntryList) find(addr Address) int { +func (l addressMapEntryList[T]) find(addr Address) int { for i, entry := range l { // Attributes are the only thing to match on here, since `Addr` and // `ServerName` are already equal. @@ -75,28 +88,28 @@ func (l addressMapEntryList) find(addr Address) int { } // Get returns the value for the address in the map, if present. -func (a *AddressMap) Get(addr Address) (value any, ok bool) { +func (a *AddressMapV2[T]) Get(addr Address) (value T, ok bool) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { return entryList[entry].value, true } - return nil, false + return value, false } // Set updates or adds the value to the address in the map. -func (a *AddressMap) Set(addr Address, value any) { +func (a *AddressMapV2[T]) Set(addr Address, value T) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] if entry := entryList.find(addr); entry != -1 { entryList[entry].value = value return } - a.m[addrKey] = append(entryList, &addressMapEntry{addr: addr, value: value}) + a.m[addrKey] = append(entryList, &addressMapEntry[T]{addr: addr, value: value}) } // Delete removes addr from the map. -func (a *AddressMap) Delete(addr Address) { +func (a *AddressMapV2[T]) Delete(addr Address) { addrKey := toMapKey(&addr) entryList := a.m[addrKey] entry := entryList.find(addr) @@ -113,7 +126,7 @@ func (a *AddressMap) Delete(addr Address) { } // Len returns the number of entries in the map. -func (a *AddressMap) Len() int { +func (a *AddressMapV2[T]) Len() int { ret := 0 for _, entryList := range a.m { ret += len(entryList) @@ -122,7 +135,7 @@ func (a *AddressMap) Len() int { } // Keys returns a slice of all current map keys. -func (a *AddressMap) Keys() []Address { +func (a *AddressMapV2[T]) Keys() []Address { ret := make([]Address, 0, a.Len()) for _, entryList := range a.m { for _, entry := range entryList { @@ -133,8 +146,8 @@ func (a *AddressMap) Keys() []Address { } // Values returns a slice of all current map values. -func (a *AddressMap) Values() []any { - ret := make([]any, 0, a.Len()) +func (a *AddressMapV2[T]) Values() []T { + ret := make([]T, 0, a.Len()) for _, entryList := range a.m { for _, entry := range entryList { ret = append(ret, entry.value) @@ -149,21 +162,21 @@ type endpointMapKey string // unordered set of address strings within an endpoint. This map is not thread // safe, thus it is unsafe to access concurrently. Must be created via // NewEndpointMap; do not construct directly. -type EndpointMap struct { - endpoints map[endpointMapKey]endpointData +type EndpointMap[T any] struct { + endpoints map[endpointMapKey]endpointData[T] } -type endpointData struct { +type endpointData[T any] struct { // decodedKey stores the original key to avoid decoding when iterating on // EndpointMap keys. decodedKey Endpoint - value any + value T } // NewEndpointMap creates a new EndpointMap. -func NewEndpointMap() *EndpointMap { - return &EndpointMap{ - endpoints: make(map[endpointMapKey]endpointData), +func NewEndpointMap[T any]() *EndpointMap[T] { + return &EndpointMap[T]{ + endpoints: make(map[endpointMapKey]endpointData[T]), } } @@ -183,25 +196,25 @@ func encodeEndpoint(e Endpoint) endpointMapKey { } // Get returns the value for the address in the map, if present. -func (em *EndpointMap) Get(e Endpoint) (value any, ok bool) { +func (em *EndpointMap[T]) Get(e Endpoint) (value T, ok bool) { val, found := em.endpoints[encodeEndpoint(e)] if found { return val.value, true } - return nil, false + return value, false } // Set updates or adds the value to the address in the map. -func (em *EndpointMap) Set(e Endpoint, value any) { +func (em *EndpointMap[T]) Set(e Endpoint, value T) { en := encodeEndpoint(e) - em.endpoints[en] = endpointData{ + em.endpoints[en] = endpointData[T]{ decodedKey: Endpoint{Addresses: e.Addresses}, value: value, } } // Len returns the number of entries in the map. -func (em *EndpointMap) Len() int { +func (em *EndpointMap[T]) Len() int { return len(em.endpoints) } @@ -210,7 +223,7 @@ func (em *EndpointMap) Len() int { // the unordered set of addresses. Thus, endpoint information returned is not // the full endpoint data (drops duplicated addresses and attributes) but can be // used for EndpointMap accesses. -func (em *EndpointMap) Keys() []Endpoint { +func (em *EndpointMap[T]) Keys() []Endpoint { ret := make([]Endpoint, 0, len(em.endpoints)) for _, en := range em.endpoints { ret = append(ret, en.decodedKey) @@ -219,8 +232,8 @@ func (em *EndpointMap) Keys() []Endpoint { } // Values returns a slice of all current map values. -func (em *EndpointMap) Values() []any { - ret := make([]any, 0, len(em.endpoints)) +func (em *EndpointMap[T]) Values() []T { + ret := make([]T, 0, len(em.endpoints)) for _, val := range em.endpoints { ret = append(ret, val.value) } @@ -228,7 +241,7 @@ func (em *EndpointMap) Values() []any { } // Delete removes the specified endpoint from the map. -func (em *EndpointMap) Delete(e Endpoint) { +func (em *EndpointMap[T]) Delete(e Endpoint) { en := encodeEndpoint(e) delete(em.endpoints, en) } diff --git a/e2e/vendor/google.golang.org/grpc/stats/stats.go b/e2e/vendor/google.golang.org/grpc/stats/stats.go index 6f20d2d54..baf7740ef 100644 --- a/e2e/vendor/google.golang.org/grpc/stats/stats.go +++ b/e2e/vendor/google.golang.org/grpc/stats/stats.go @@ -36,7 +36,12 @@ type RPCStats interface { IsClient() bool } -// Begin contains stats when an RPC attempt begins. +// Begin contains stats for the start of an RPC attempt. +// +// - Server-side: Triggered after `InHeader`, as headers are processed +// before the RPC lifecycle begins. +// - Client-side: The first stats event recorded. +// // FailFast is only valid if this Begin is from client side. type Begin struct { // Client is true if this Begin is from client side. @@ -69,7 +74,7 @@ func (*PickerUpdated) IsClient() bool { return true } func (*PickerUpdated) isRPCStats() {} -// InPayload contains the information for an incoming payload. +// InPayload contains stats about an incoming payload. type InPayload struct { // Client is true if this InPayload is from client side. Client bool @@ -98,7 +103,9 @@ func (s *InPayload) IsClient() bool { return s.Client } func (s *InPayload) isRPCStats() {} -// InHeader contains stats when a header is received. +// InHeader contains stats about header reception. +// +// - Server-side: The first stats event after the RPC request is received. type InHeader struct { // Client is true if this InHeader is from client side. Client bool @@ -123,7 +130,7 @@ func (s *InHeader) IsClient() bool { return s.Client } func (s *InHeader) isRPCStats() {} -// InTrailer contains stats when a trailer is received. +// InTrailer contains stats about trailer reception. type InTrailer struct { // Client is true if this InTrailer is from client side. Client bool @@ -139,7 +146,7 @@ func (s *InTrailer) IsClient() bool { return s.Client } func (s *InTrailer) isRPCStats() {} -// OutPayload contains the information for an outgoing payload. +// OutPayload contains stats about an outgoing payload. type OutPayload struct { // Client is true if this OutPayload is from client side. Client bool @@ -166,7 +173,10 @@ func (s *OutPayload) IsClient() bool { return s.Client } func (s *OutPayload) isRPCStats() {} -// OutHeader contains stats when a header is sent. +// OutHeader contains stats about header transmission. +// +// - Client-side: Only occurs after 'Begin', as headers are always the first +// thing sent on a stream. type OutHeader struct { // Client is true if this OutHeader is from client side. Client bool @@ -189,14 +199,15 @@ func (s *OutHeader) IsClient() bool { return s.Client } func (s *OutHeader) isRPCStats() {} -// OutTrailer contains stats when a trailer is sent. +// OutTrailer contains stats about trailer transmission. type OutTrailer struct { // Client is true if this OutTrailer is from client side. Client bool // WireLength is the wire length of trailer. // - // Deprecated: This field is never set. The length is not known when this message is - // emitted because the trailer fields are compressed with hpack after that. + // Deprecated: This field is never set. The length is not known when this + // message is emitted because the trailer fields are compressed with hpack + // after that. WireLength int // Trailer contains the trailer metadata sent to the client. This // field is only valid if this OutTrailer is from the server side. @@ -208,7 +219,7 @@ func (s *OutTrailer) IsClient() bool { return s.Client } func (s *OutTrailer) isRPCStats() {} -// End contains stats when an RPC ends. +// End contains stats about RPC completion. type End struct { // Client is true if this End is from client side. Client bool @@ -238,7 +249,7 @@ type ConnStats interface { IsClient() bool } -// ConnBegin contains the stats of a connection when it is established. +// ConnBegin contains stats about connection establishment. type ConnBegin struct { // Client is true if this ConnBegin is from client side. Client bool @@ -249,7 +260,7 @@ func (s *ConnBegin) IsClient() bool { return s.Client } func (s *ConnBegin) isConnStats() {} -// ConnEnd contains the stats of a connection when it ends. +// ConnEnd contains stats about connection termination. type ConnEnd struct { // Client is true if this ConnEnd is from client side. Client bool diff --git a/e2e/vendor/google.golang.org/grpc/version.go b/e2e/vendor/google.golang.org/grpc/version.go index 3c148a814..90237b1db 100644 --- a/e2e/vendor/google.golang.org/grpc/version.go +++ b/e2e/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.71.1" +const Version = "1.72.0" diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go index 167baf680..58751ed0e 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/errors/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package errors provides detailed error types for api field validation. -package errors // import "k8s.io/apimachinery/pkg/api/errors" +package errors diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go index b6d42acf8..a3b18a5c9 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package meta provides functions for retrieving API metadata from objects // belonging to the Kubernetes API -package meta // import "k8s.io/apimachinery/pkg/api/meta" +package meta diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/help.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/help.go index 1fdd32c4b..468afd0e9 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/help.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/meta/help.go @@ -221,6 +221,9 @@ func extractList(obj runtime.Object, allocNew bool) ([]runtime.Object, error) { if err != nil { return nil, err } + if items.IsNil() { + return nil, nil + } list := make([]runtime.Object, items.Len()) if len(list) == 0 { return list, nil diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go new file mode 100644 index 000000000..9f5ae7a9d --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/operation/operation.go @@ -0,0 +1,56 @@ +/* +Copyright 2024 The Kubernetes 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 operation + +import "k8s.io/apimachinery/pkg/util/sets" + +// Operation provides contextual information about a validation request and the API +// operation being validated. +// This type is intended for use with generate validation code and may be enhanced +// in the future to include other information needed to validate requests. +type Operation struct { + // Type is the category of operation being validated. This does not + // differentiate between HTTP verbs like PUT and PATCH, but rather merges + // those into a single "Update" category. + Type Type + + // Options declare the options enabled for validation. + // + // Options should be set according to a resource validation strategy before validation + // is performed, and must be treated as read-only during validation. + // + // Options are identified by string names. Option string names may match the name of a feature + // gate, in which case the presence of the name in the set indicates that the feature is + // considered enabled for the resource being validated. Note that a resource may have a + // feature enabled even when the feature gate is disabled. This can happen when feature is + // already in-use by a resource, often because the feature gate was enabled when the + // resource first began using the feature. + // + // Unset options are disabled/false. + Options sets.Set[string] +} + +// Code is the request operation to be validated. +type Type uint32 + +const ( + // Create indicates the request being validated is for a resource create operation. + Create Type = iota + + // Update indicates the request being validated is for a resource update operation. + Update +) diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go index 9f20152e4..9e305b0b1 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package validation contains generic api type validation functions. -package validation // import "k8s.io/apimachinery/pkg/api/validation" +package validation diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go b/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go index e0b5b1490..f9cada1f0 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/api/validation/generic.go @@ -82,7 +82,7 @@ func maskTrailingDash(name string) string { func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if value < 0 { - allErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg)) + allErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg).WithOrigin("minimum")) } return allErrs } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/asn1/oid.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/asn1/oid.go new file mode 100644 index 000000000..59c363f91 --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/asn1/oid.go @@ -0,0 +1,43 @@ +/* +Copyright 2024 The Kubernetes 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 asn1 + +import "encoding/asn1" + +// These constants store suffixes for use with the CNCF Private Enterprise Number allocated to Kubernetes: +// https://www.iana.org/assignments/enterprise-numbers.txt +// +// Root: 1.3.6.1.4.1.57683 +// +// Cloud Native Computing Foundation +const ( + // single-value, string value + x509UIDSuffix = 2 +) + +func makeOID(suffix int) asn1.ObjectIdentifier { + return asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57683, suffix} +} + +// X509UID returns an OID (1.3.6.1.4.1.57683.2) for an element of an x509 distinguished name representing a user UID. +// The UID is a unique value for a particular user that will change if the user is removed from the system +// and another user is added with the same username. +// +// This element must not appear more than once in a distinguished name, and the value must be a string +func X509UID() asn1.ObjectIdentifier { + return makeOID(x509UIDSuffix) +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go index 2741ee2c8..1e85c5c43 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +k8s:conversion-gen=k8s.io/apimachinery/pkg/apis/meta/v1 -package internalversion // import "k8s.io/apimachinery/pkg/apis/meta/internalversion" +package internalversion diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme/doc.go index a45fa2a8a..b5ce956ee 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme/doc.go @@ -14,4 +14,4 @@ See the License for the specific language governing permissions and limitations under the License. */ -package scheme // import "k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme" +package scheme diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go index 00d2b8c68..8c60e7d2a 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/types.go @@ -41,8 +41,6 @@ type ListOptions struct { // assume bookmarks are returned at any specific interval, nor may they // assume the server will send any BOOKMARK event during a session. // If this is not a watch, this field is ignored. - // If the feature gate WatchBookmarks is not enabled in apiserver, - // this field is ignored. AllowWatchBookmarks bool // resourceVersion sets a constraint on what resource versions a request may be served from. // See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/doc.go index 7736753d6..617b9a5d3 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/doc.go @@ -21,4 +21,4 @@ limitations under the License. // +groupName=meta.k8s.io -package v1 // import "k8s.io/apimachinery/pkg/apis/meta/v1" +package v1 diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go index 3cf9d48e9..a5f437b4b 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go @@ -20,21 +20,22 @@ limitations under the License. package v1 import ( + "math/rand" "time" - fuzz "github.com/google/gofuzz" + "sigs.k8s.io/randfill" ) -// Fuzz satisfies fuzz.Interface. -func (t *MicroTime) Fuzz(c fuzz.Continue) { +// Fuzz satisfies randfill.SimpleSelfFiller. +func (t *MicroTime) RandFill(r *rand.Rand) { if t == nil { return } // Allow for about 1000 years of randomness. Accurate to a tenth of // micro second. Leave off nanoseconds because JSON doesn't // represent them so they can't round-trip properly. - t.Time = time.Unix(c.Rand.Int63n(1000*365*24*60*60), 1000*c.Rand.Int63n(1000000)) + t.Time = time.Unix(r.Int63n(1000*365*24*60*60), 1000*r.Int63n(1000000)) } -// ensure MicroTime implements fuzz.Interface -var _ fuzz.Interface = &MicroTime{} +// ensure MicroTime implements randfill.Interface +var _ randfill.SimpleSelfFiller = &MicroTime{} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go index bf9e21b5b..48fb97845 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go @@ -20,21 +20,22 @@ limitations under the License. package v1 import ( + "math/rand" "time" - fuzz "github.com/google/gofuzz" + "sigs.k8s.io/randfill" ) -// Fuzz satisfies fuzz.Interface. -func (t *Time) Fuzz(c fuzz.Continue) { +// Fuzz satisfies randfill.SimpleSelfFiller. +func (t *Time) RandFill(r *rand.Rand) { if t == nil { return } // Allow for about 1000 years of randomness. Leave off nanoseconds // because JSON doesn't represent them so they can't round-trip // properly. - t.Time = time.Unix(c.Rand.Int63n(1000*365*24*60*60), 0) + t.Time = time.Unix(r.Int63n(1000*365*24*60*60), 0) } -// ensure Time implements fuzz.Interface -var _ fuzz.Interface = &Time{} +// ensure Time implements randfill.SimpleSelfFiller +var _ randfill.SimpleSelfFiller = &Time{} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go index 71f7b163a..59f43b7bf 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go @@ -188,7 +188,7 @@ func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, b // NestedStringMap returns a copy of map[string]string value of a nested field. // Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map. func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) { - m, found, err := nestedMapNoCopy(obj, fields...) + m, found, err := nestedMapNoCopy(obj, false, fields...) if !found || err != nil { return nil, found, err } @@ -203,10 +203,32 @@ func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]s return strMap, true, nil } +// NestedNullCoercingStringMap returns a copy of map[string]string value of a nested field. +// Returns `nil, true, nil` if the value exists and is explicitly null. +// Returns `nil, false, err` if the value is not a map or a null value, or is a map and contains non-string non-null values. +// Null values in the map are coerced to "" to match json decoding behavior. +func NestedNullCoercingStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) { + m, found, err := nestedMapNoCopy(obj, true, fields...) + if !found || err != nil || m == nil { + return nil, found, err + } + strMap := make(map[string]string, len(m)) + for k, v := range m { + if str, ok := v.(string); ok { + strMap[k] = str + } else if v == nil { + strMap[k] = "" + } else { + return nil, false, fmt.Errorf("%v accessor error: contains non-string value in the map under key %q: %v is of the type %T, expected string", jsonPath(fields), k, v, v) + } + } + return strMap, true, nil +} + // NestedMap returns a deep copy of map[string]interface{} value of a nested field. // Returns false if value is not found and an error if not a map[string]interface{}. func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) { - m, found, err := nestedMapNoCopy(obj, fields...) + m, found, err := nestedMapNoCopy(obj, false, fields...) if !found || err != nil { return nil, found, err } @@ -215,11 +237,14 @@ func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interfa // nestedMapNoCopy returns a map[string]interface{} value of a nested field. // Returns false if value is not found and an error if not a map[string]interface{}. -func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) { +func nestedMapNoCopy(obj map[string]interface{}, tolerateNil bool, fields ...string) (map[string]interface{}, bool, error) { val, found, err := NestedFieldNoCopy(obj, fields...) if !found || err != nil { return nil, found, err } + if val == nil && tolerateNil { + return nil, true, nil + } m, ok := val.(map[string]interface{}) if !ok { return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]interface{}", jsonPath(fields), val, val) diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go index 5e36a91ee..fdb0c8629 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go @@ -397,7 +397,7 @@ func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds } func (u *Unstructured) GetLabels() map[string]string { - m, _, _ := NestedStringMap(u.Object, "metadata", "labels") + m, _, _ := NestedNullCoercingStringMap(u.Object, "metadata", "labels") return m } @@ -410,7 +410,7 @@ func (u *Unstructured) SetLabels(labels map[string]string) { } func (u *Unstructured) GetAnnotations() map[string]string { - m, _, _ := NestedStringMap(u.Object, "metadata", "annotations") + m, _, _ := NestedNullCoercingStringMap(u.Object, "metadata", "annotations") return m } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go index b1eb1bbfc..95240b74d 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go @@ -104,7 +104,7 @@ func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, opts L func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} for _, msg := range validation.IsQualifiedName(labelName) { - allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg)) + allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg).WithOrigin("labelKey")) } return allErrs } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go index 20c9d2ec7..46b0e133c 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +groupName=meta.k8s.io -package v1beta1 // import "k8s.io/apimachinery/pkg/apis/meta/v1beta1" +package v1beta1 diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/conversion/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/conversion/doc.go index 7415d8164..0c46ef2d1 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/conversion/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/conversion/doc.go @@ -21,4 +21,4 @@ limitations under the License. // but for the fields which did not change, copying is automated. This makes it // easy to modify the structures you use in memory without affecting the format // you store on disk or respond to in your external API calls. -package conversion // import "k8s.io/apimachinery/pkg/conversion" +package conversion diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/doc.go index 7b763de6f..4c1002a4c 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package queryparams provides conversion from versioned // runtime objects to URL query values -package queryparams // import "k8s.io/apimachinery/pkg/conversion/queryparams" +package queryparams diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/fields/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/fields/doc.go index c39b8039a..49059e263 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/fields/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/fields/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package fields implements a simple field system, parsing and matching // selectors with sets of fields. -package fields // import "k8s.io/apimachinery/pkg/fields" +package fields diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/labels/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/labels/doc.go index 82de0051b..35ba78809 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/labels/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/labels/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package labels implements a simple label system, parsing and matching // selectors with sets of labels. -package labels // import "k8s.io/apimachinery/pkg/labels" +package labels diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/doc.go index 89feb4010..b54429bd8 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/doc.go @@ -48,4 +48,4 @@ limitations under the License. // // As a bonus, a few common types useful from all api objects and versions // are provided in types.go. -package runtime // import "k8s.io/apimachinery/pkg/runtime" +package runtime diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go index 2703300cd..202bf4f01 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go @@ -259,6 +259,7 @@ type ObjectDefaulter interface { type ObjectVersioner interface { ConvertToVersion(in Object, gv GroupVersioner) (out Object, err error) + PrioritizedVersionsForGroup(group string) []schema.GroupVersion } // ObjectConvertor converts an object to a different version. diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go index a5b116718..fde87f1a1 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/scheme.go @@ -17,15 +17,18 @@ limitations under the License. package runtime import ( + "context" "fmt" "reflect" "strings" + "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/naming" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/validation/field" ) // Scheme defines methods for serializing and deserializing API objects, a type @@ -68,6 +71,12 @@ type Scheme struct { // the provided object must be a pointer. defaulterFuncs map[reflect.Type]func(interface{}) + // validationFuncs is a map to funcs to be called with an object to perform validation. + // The provided object must be a pointer. + // If oldObject is non-nil, update validation is performed and may perform additional + // validation such as transition rules and immutability checks. + validationFuncs map[reflect.Type]func(ctx context.Context, op operation.Operation, object, oldObject interface{}, subresources ...string) field.ErrorList + // converter stores all registered conversion functions. It also has // default converting behavior. converter *conversion.Converter @@ -96,6 +105,7 @@ func NewScheme() *Scheme { unversionedKinds: map[string]reflect.Type{}, fieldLabelConversionFuncs: map[schema.GroupVersionKind]FieldLabelConversionFunc{}, defaulterFuncs: map[reflect.Type]func(interface{}){}, + validationFuncs: map[reflect.Type]func(ctx context.Context, op operation.Operation, object, oldObject interface{}, subresource ...string) field.ErrorList{}, versionPriority: map[string][]string{}, schemeName: naming.GetNameFromCallsite(internalPackages...), } @@ -347,6 +357,35 @@ func (s *Scheme) Default(src Object) { } } +// AddValidationFunc registered a function that can validate the object, and +// oldObject. These functions will be invoked when Validate() or ValidateUpdate() +// is called. The function will never be called unless the validated object +// matches srcType. If this function is invoked twice with the same srcType, the +// fn passed to the later call will be used instead. +func (s *Scheme) AddValidationFunc(srcType Object, fn func(ctx context.Context, op operation.Operation, object, oldObject interface{}, subresources ...string) field.ErrorList) { + s.validationFuncs[reflect.TypeOf(srcType)] = fn +} + +// Validate validates the provided Object according to the generated declarative validation code. +// WARNING: This does not validate all objects! The handwritten validation code in validation.go +// is not run when this is called. Only the generated zz_generated.validations.go validation code is run. +func (s *Scheme) Validate(ctx context.Context, options sets.Set[string], object Object, subresources ...string) field.ErrorList { + if fn, ok := s.validationFuncs[reflect.TypeOf(object)]; ok { + return fn(ctx, operation.Operation{Type: operation.Create, Options: options}, object, nil, subresources...) + } + return nil +} + +// ValidateUpdate validates the provided object and oldObject according to the generated declarative validation code. +// WARNING: This does not validate all objects! The handwritten validation code in validation.go +// is not run when this is called. Only the generated zz_generated.validations.go validation code is run. +func (s *Scheme) ValidateUpdate(ctx context.Context, options sets.Set[string], object, oldObject Object, subresources ...string) field.ErrorList { + if fn, ok := s.validationFuncs[reflect.TypeOf(object)]; ok { + return fn(ctx, operation.Operation{Type: operation.Update, Options: options}, object, oldObject, subresources...) + } + return nil +} + // Convert will attempt to convert in into out. Both must be pointers. For easy // testing of conversion functions. Returns an error if the conversion isn't // possible. You can call this with types that haven't been registered (for example, diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/custom.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/custom.go index 858529e95..e550ea348 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/custom.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/cbor/internal/modes/custom.go @@ -140,7 +140,7 @@ func (cache *checkers) getCheckerInternal(rt reflect.Type, parent *path) (c chec var wg sync.WaitGroup wg.Add(1) defer wg.Done() - c = checker{ + placeholder := checker{ safe: func() bool { wg.Wait() return c.safe() @@ -150,7 +150,7 @@ func (cache *checkers) getCheckerInternal(rt reflect.Type, parent *path) (c chec return c.check(rv, depth) }, } - if actual, loaded := cache.m.LoadOrStore(rt, &c); loaded { + if actual, loaded := cache.m.LoadOrStore(rt, &placeholder); loaded { // Someone else stored an entry for this type, use it. return *actual.(*checker) } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go index 77bb30745..81286fccb 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go @@ -28,7 +28,7 @@ import ( func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, options CodecFactoryOptions) []runtime.SerializerInfo { jsonSerializer := json.NewSerializerWithOptions( mf, scheme, scheme, - json.SerializerOptions{Yaml: false, Pretty: false, Strict: options.Strict}, + json.SerializerOptions{Yaml: false, Pretty: false, Strict: options.Strict, StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToJSON}, ) jsonSerializerType := runtime.SerializerInfo{ MediaType: runtime.ContentTypeJSON, @@ -38,7 +38,7 @@ func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, option Serializer: jsonSerializer, StrictSerializer: json.NewSerializerWithOptions( mf, scheme, scheme, - json.SerializerOptions{Yaml: false, Pretty: false, Strict: true}, + json.SerializerOptions{Yaml: false, Pretty: false, Strict: true, StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToJSON}, ), StreamSerializer: &runtime.StreamSerializerInfo{ EncodesAsText: true, @@ -61,7 +61,9 @@ func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, option mf, scheme, scheme, json.SerializerOptions{Yaml: true, Pretty: false, Strict: true}, ) - protoSerializer := protobuf.NewSerializer(scheme, scheme) + protoSerializer := protobuf.NewSerializerWithOptions(scheme, scheme, protobuf.SerializerOptions{ + StreamingCollectionsEncoding: options.StreamingCollectionsEncodingToProtobuf, + }) protoRawSerializer := protobuf.NewRawSerializer(scheme, scheme) serializers := []runtime.SerializerInfo{ @@ -113,6 +115,9 @@ type CodecFactoryOptions struct { // Pretty includes a pretty serializer along with the non-pretty one Pretty bool + StreamingCollectionsEncodingToJSON bool + StreamingCollectionsEncodingToProtobuf bool + serializers []func(runtime.ObjectCreater, runtime.ObjectTyper) runtime.SerializerInfo } @@ -147,6 +152,18 @@ func WithSerializer(f func(runtime.ObjectCreater, runtime.ObjectTyper) runtime.S } } +func WithStreamingCollectionEncodingToJSON() CodecFactoryOptionsMutator { + return func(options *CodecFactoryOptions) { + options.StreamingCollectionsEncodingToJSON = true + } +} + +func WithStreamingCollectionEncodingToProtobuf() CodecFactoryOptionsMutator { + return func(options *CodecFactoryOptions) { + options.StreamingCollectionsEncodingToProtobuf = true + } +} + // NewCodecFactory provides methods for retrieving serializers for the supported wire formats // and conversion wrappers to define preferred internal and external versions. In the future, // as the internal version is used less, callers may instead use a defaulting serializer and diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go new file mode 100644 index 000000000..075163ddd --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/collections.go @@ -0,0 +1,230 @@ +/* +Copyright 2025 The Kubernetes 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 json + +import ( + "encoding/json" + "fmt" + "io" + "maps" + "slices" + "sort" + + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/conversion" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" +) + +func streamEncodeCollections(obj runtime.Object, w io.Writer) (bool, error) { + list, ok := obj.(*unstructured.UnstructuredList) + if ok { + return true, streamingEncodeUnstructuredList(w, list) + } + if _, ok := obj.(json.Marshaler); ok { + return false, nil + } + typeMeta, listMeta, items, err := getListMeta(obj) + if err == nil { + return true, streamingEncodeList(w, typeMeta, listMeta, items) + } + return false, nil +} + +// getListMeta implements list extraction logic for json stream serialization. +// +// Reason for a custom logic instead of reusing accessors from meta package: +// * Validate json tags to prevent incompatibility with json standard package. +// * ListMetaAccessor doesn't distinguish empty from nil value. +// * TypeAccessort reparsing "apiVersion" and serializing it with "{group}/{version}" +func getListMeta(list runtime.Object) (metav1.TypeMeta, metav1.ListMeta, []runtime.Object, error) { + listValue, err := conversion.EnforcePtr(list) + if err != nil { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, err + } + listType := listValue.Type() + if listType.NumField() != 3 { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected ListType to have 3 fields") + } + // TypeMeta + typeMeta, ok := listValue.Field(0).Interface().(metav1.TypeMeta) + if !ok { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected TypeMeta field to have TypeMeta type") + } + if listType.Field(0).Tag.Get("json") != ",inline" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected TypeMeta json field tag to be ",inline"`) + } + // ListMeta + listMeta, ok := listValue.Field(1).Interface().(metav1.ListMeta) + if !ok { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf("expected ListMeta field to have ListMeta type") + } + if listType.Field(1).Tag.Get("json") != "metadata,omitempty" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected ListMeta json field tag to be "metadata,omitempty"`) + } + // Items + items, err := meta.ExtractList(list) + if err != nil { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, err + } + if listType.Field(2).Tag.Get("json") != "items" { + return metav1.TypeMeta{}, metav1.ListMeta{}, nil, fmt.Errorf(`expected Items json field tag to be "items"`) + } + return typeMeta, listMeta, items, nil +} + +func streamingEncodeList(w io.Writer, typeMeta metav1.TypeMeta, listMeta metav1.ListMeta, items []runtime.Object) error { + // Start + if _, err := w.Write([]byte(`{`)); err != nil { + return err + } + + // TypeMeta + if typeMeta.Kind != "" { + if err := encodeKeyValuePair(w, "kind", typeMeta.Kind, []byte(",")); err != nil { + return err + } + } + if typeMeta.APIVersion != "" { + if err := encodeKeyValuePair(w, "apiVersion", typeMeta.APIVersion, []byte(",")); err != nil { + return err + } + } + + // ListMeta + if err := encodeKeyValuePair(w, "metadata", listMeta, []byte(",")); err != nil { + return err + } + + // Items + if err := encodeItemsObjectSlice(w, items); err != nil { + return err + } + + // End + _, err := w.Write([]byte("}\n")) + return err +} + +func encodeItemsObjectSlice(w io.Writer, items []runtime.Object) (err error) { + if items == nil { + err := encodeKeyValuePair(w, "items", nil, nil) + return err + } + _, err = w.Write([]byte(`"items":[`)) + if err != nil { + return err + } + suffix := []byte(",") + for i, item := range items { + if i == len(items)-1 { + suffix = nil + } + err := encodeValue(w, item, suffix) + if err != nil { + return err + } + } + _, err = w.Write([]byte("]")) + if err != nil { + return err + } + return err +} + +func streamingEncodeUnstructuredList(w io.Writer, list *unstructured.UnstructuredList) error { + _, err := w.Write([]byte(`{`)) + if err != nil { + return err + } + keys := slices.Collect(maps.Keys(list.Object)) + if _, exists := list.Object["items"]; !exists { + keys = append(keys, "items") + } + sort.Strings(keys) + + suffix := []byte(",") + for i, key := range keys { + if i == len(keys)-1 { + suffix = nil + } + if key == "items" { + err = encodeItemsUnstructuredSlice(w, list.Items, suffix) + } else { + err = encodeKeyValuePair(w, key, list.Object[key], suffix) + } + if err != nil { + return err + } + } + _, err = w.Write([]byte("}\n")) + return err +} + +func encodeItemsUnstructuredSlice(w io.Writer, items []unstructured.Unstructured, suffix []byte) (err error) { + _, err = w.Write([]byte(`"items":[`)) + if err != nil { + return err + } + comma := []byte(",") + for i, item := range items { + if i == len(items)-1 { + comma = nil + } + err := encodeValue(w, item.Object, comma) + if err != nil { + return err + } + } + _, err = w.Write([]byte("]")) + if err != nil { + return err + } + if len(suffix) > 0 { + _, err = w.Write(suffix) + } + return err +} + +func encodeKeyValuePair(w io.Writer, key string, value any, suffix []byte) (err error) { + err = encodeValue(w, key, []byte(":")) + if err != nil { + return err + } + err = encodeValue(w, value, suffix) + if err != nil { + return err + } + return err +} + +func encodeValue(w io.Writer, value any, suffix []byte) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + _, err = w.Write(data) + if err != nil { + return err + } + if len(suffix) > 0 { + _, err = w.Write(suffix) + } + return err +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go index 1ae4a32eb..24f66a101 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go @@ -36,7 +36,7 @@ import ( // is not nil, the object has the group, version, and kind fields set. // Deprecated: use NewSerializerWithOptions instead. func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer { - return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false}) + return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false, false}) } // NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer @@ -44,7 +44,7 @@ func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtim // matches JSON, and will error if constructs are used that do not serialize to JSON. // Deprecated: use NewSerializerWithOptions instead. func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer { - return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false}) + return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false, false}) } // NewSerializerWithOptions creates a JSON/YAML serializer that handles encoding versioned objects into the proper JSON/YAML @@ -93,6 +93,9 @@ type SerializerOptions struct { // Strict: configures the Serializer to return strictDecodingError's when duplicate fields are present decoding JSON or YAML. // Note that enabling this option is not as performant as the non-strict variant, and should not be used in fast paths. Strict bool + + // StreamingCollectionsEncoding enables encoding collection, one item at the time, drastically reducing memory needed. + StreamingCollectionsEncoding bool } // Serializer handles encoding versioned objects into the proper JSON form @@ -242,6 +245,15 @@ func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error { _, err = w.Write(data) return err } + if s.options.StreamingCollectionsEncoding { + ok, err := streamEncodeCollections(obj, w) + if err != nil { + return err + } + if ok { + return nil + } + } encoder := json.NewEncoder(w) return encoder.Encode(obj) } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go new file mode 100644 index 000000000..754a80820 --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/collections.go @@ -0,0 +1,174 @@ +/* +Copyright 2025 The Kubernetes 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 protobuf + +import ( + "errors" + "io" + "math/bits" + + "github.com/gogo/protobuf/proto" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/conversion" + "k8s.io/apimachinery/pkg/runtime" +) + +var ( + errFieldCount = errors.New("expected ListType to have 3 fields") + errTypeMetaField = errors.New("expected TypeMeta field to have TypeMeta type") + errTypeMetaProtobufTag = errors.New(`expected TypeMeta protobuf field tag to be ""`) + errListMetaField = errors.New("expected ListMeta field to have ListMeta type") + errListMetaProtobufTag = errors.New(`expected ListMeta protobuf field tag to be "bytes,1,opt,name=metadata"`) + errItemsProtobufTag = errors.New(`expected Items protobuf field tag to be "bytes,2,rep,name=items"`) + errItemsSizer = errors.New(`expected Items elements to implement proto.Sizer`) +) + +// getStreamingListData implements list extraction logic for protobuf stream serialization. +// +// Reason for a custom logic instead of reusing accessors from meta package: +// * Validate proto tags to prevent incompatibility with proto standard package. +// * ListMetaAccessor doesn't distinguish empty from nil value. +// * TypeAccessor reparsing "apiVersion" and serializing it with "{group}/{version}" +func getStreamingListData(list runtime.Object) (data streamingListData, err error) { + listValue, err := conversion.EnforcePtr(list) + if err != nil { + return data, err + } + listType := listValue.Type() + if listType.NumField() != 3 { + return data, errFieldCount + } + // TypeMeta: validated, but not returned as is not serialized. + _, ok := listValue.Field(0).Interface().(metav1.TypeMeta) + if !ok { + return data, errTypeMetaField + } + if listType.Field(0).Tag.Get("protobuf") != "" { + return data, errTypeMetaProtobufTag + } + // ListMeta + listMeta, ok := listValue.Field(1).Interface().(metav1.ListMeta) + if !ok { + return data, errListMetaField + } + // if we were ever to relax the protobuf tag check we should update the hardcoded `0xa` below when writing ListMeta. + if listType.Field(1).Tag.Get("protobuf") != "bytes,1,opt,name=metadata" { + return data, errListMetaProtobufTag + } + data.listMeta = listMeta + // Items; if we were ever to relax the protobuf tag check we should update the hardcoded `0x12` below when writing Items. + if listType.Field(2).Tag.Get("protobuf") != "bytes,2,rep,name=items" { + return data, errItemsProtobufTag + } + items, err := meta.ExtractList(list) + if err != nil { + return data, err + } + data.items = items + data.totalSize, data.listMetaSize, data.itemsSizes, err = listSize(listMeta, items) + return data, err +} + +type streamingListData struct { + // totalSize is the total size of the serialized List object, including their proto headers/size bytes + totalSize int + + // listMetaSize caches results from .Size() call to listMeta, doesn't include header bytes (field identifier, size) + listMetaSize int + listMeta metav1.ListMeta + + // itemsSizes caches results from .Size() call to items, doesn't include header bytes (field identifier, size) + itemsSizes []int + items []runtime.Object +} + +// listSize return size of ListMeta and items to be later used for preallocations. +// listMetaSize and itemSizes do not include header bytes (field identifier, size). +func listSize(listMeta metav1.ListMeta, items []runtime.Object) (totalSize, listMetaSize int, itemSizes []int, err error) { + // ListMeta + listMetaSize = listMeta.Size() + totalSize += 1 + sovGenerated(uint64(listMetaSize)) + listMetaSize + // Items + itemSizes = make([]int, len(items)) + for i, item := range items { + sizer, ok := item.(proto.Sizer) + if !ok { + return totalSize, listMetaSize, nil, errItemsSizer + } + n := sizer.Size() + itemSizes[i] = n + totalSize += 1 + sovGenerated(uint64(n)) + n + } + return totalSize, listMetaSize, itemSizes, nil +} + +func streamingEncodeUnknownList(w io.Writer, unk runtime.Unknown, listData streamingListData, memAlloc runtime.MemoryAllocator) error { + _, err := w.Write(protoEncodingPrefix) + if err != nil { + return err + } + // encodeList is responsible for encoding the List into the unknown Raw. + encodeList := func(writer io.Writer) (int, error) { + return streamingEncodeList(writer, listData, memAlloc) + } + _, err = unk.MarshalToWriter(w, listData.totalSize, encodeList) + return err +} + +func streamingEncodeList(w io.Writer, listData streamingListData, memAlloc runtime.MemoryAllocator) (size int, err error) { + // ListMeta; 0xa = (1 << 3) | 2; field number: 1, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure + n, err := doEncodeWithHeader(&listData.listMeta, w, 0xa, listData.listMetaSize, memAlloc) + size += n + if err != nil { + return size, err + } + // Items; 0x12 = (2 << 3) | 2; field number: 2, type: 2 (LEN). https://protobuf.dev/programming-guides/encoding/#structure + for i, item := range listData.items { + n, err := doEncodeWithHeader(item, w, 0x12, listData.itemsSizes[i], memAlloc) + size += n + if err != nil { + return size, err + } + } + return size, nil +} + +func writeVarintGenerated(w io.Writer, v int) (int, error) { + buf := make([]byte, sovGenerated(uint64(v))) + encodeVarintGenerated(buf, len(buf), uint64(v)) + return w.Write(buf) +} + +// sovGenerated is copied from `generated.pb.go` returns size of varint. +func sovGenerated(v uint64) int { + return (bits.Len64(v|1) + 6) / 7 +} + +// encodeVarintGenerated is copied from `generated.pb.go` encodes varint. +func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { + offset -= sovGenerated(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go index 72d0ac79b..381748d69 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package protobuf provides a Kubernetes serializer for the protobuf format. -package protobuf // import "k8s.io/apimachinery/pkg/runtime/serializer/protobuf" +package protobuf diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go index c63e6dc63..c66c49ac4 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go @@ -72,10 +72,18 @@ func IsNotMarshalable(err error) bool { // is passed, the encoded object will have group, version, and kind fields set. If typer is nil, the objects will be written // as-is (any type info passed with the object will be used). func NewSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer { + return NewSerializerWithOptions(creater, typer, SerializerOptions{}) +} + +// NewSerializerWithOptions creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If a typer +// is passed, the encoded object will have group, version, and kind fields set. If typer is nil, the objects will be written +// as-is (any type info passed with the object will be used). +func NewSerializerWithOptions(creater runtime.ObjectCreater, typer runtime.ObjectTyper, opts SerializerOptions) *Serializer { return &Serializer{ prefix: protoEncodingPrefix, creater: creater, typer: typer, + options: opts, } } @@ -84,6 +92,14 @@ type Serializer struct { prefix []byte creater runtime.ObjectCreater typer runtime.ObjectTyper + + options SerializerOptions +} + +// SerializerOptions holds the options which are used to configure a Proto serializer. +type SerializerOptions struct { + // StreamingCollectionsEncoding enables encoding collection, one item at the time, drastically reducing memory needed. + StreamingCollectionsEncoding bool } var _ runtime.Serializer = &Serializer{} @@ -209,6 +225,13 @@ func (s *Serializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime. }, } } + if s.options.StreamingCollectionsEncoding { + listData, err := getStreamingListData(obj) + if err == nil { + // Doesn't honor custom proto marshaling methods (like json streaming), because all proto objects implement proto methods. + return streamingEncodeUnknownList(w, unk, listData, memAlloc) + } + } switch t := obj.(type) { case bufferedMarshaller: @@ -428,6 +451,39 @@ func (s *RawSerializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime } func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error { + _, err := doEncode(obj, w, nil, memAlloc) + return err +} + +func doEncodeWithHeader(obj any, w io.Writer, field byte, precomputedSize int, memAlloc runtime.MemoryAllocator) (size int, err error) { + // Field identifier + n, err := w.Write([]byte{field}) + size += n + if err != nil { + return size, err + } + // Size + n, err = writeVarintGenerated(w, precomputedSize) + size += n + if err != nil { + return size, err + } + // Obj + n, err = doEncode(obj, w, &precomputedSize, memAlloc) + size += n + if err != nil { + return size, err + } + if n != precomputedSize { + return size, fmt.Errorf("the size value was %d, but doEncode wrote %d bytes to data", precomputedSize, n) + } + return size, nil +} + +// doEncode encodes provided object into writer using a allocator if possible. +// Avoids call by object Size if precomputedObjSize is provided. +// precomputedObjSize should not include header bytes (field identifier, size). +func doEncode(obj any, w io.Writer, precomputedObjSize *int, memAlloc runtime.MemoryAllocator) (int, error) { if memAlloc == nil { klog.Error("a mandatory memory allocator wasn't provided, this might have a negative impact on performance, check invocations of EncodeWithAllocator method, falling back on runtime.SimpleAllocator") memAlloc = &runtime.SimpleAllocator{} @@ -436,40 +492,43 @@ func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runti case bufferedReverseMarshaller: // this path performs a single allocation during write only when the Allocator wasn't provided // it also requires the caller to implement the more efficient Size and MarshalToSizedBuffer methods - encodedSize := uint64(t.Size()) - data := memAlloc.Allocate(encodedSize) + if precomputedObjSize == nil { + s := t.Size() + precomputedObjSize = &s + } + data := memAlloc.Allocate(uint64(*precomputedObjSize)) n, err := t.MarshalToSizedBuffer(data) if err != nil { - return err + return 0, err } - _, err = w.Write(data[:n]) - return err + return w.Write(data[:n]) case bufferedMarshaller: // this path performs a single allocation during write only when the Allocator wasn't provided // it also requires the caller to implement the more efficient Size and MarshalTo methods - encodedSize := uint64(t.Size()) - data := memAlloc.Allocate(encodedSize) + if precomputedObjSize == nil { + s := t.Size() + precomputedObjSize = &s + } + data := memAlloc.Allocate(uint64(*precomputedObjSize)) n, err := t.MarshalTo(data) if err != nil { - return err + return 0, err } - _, err = w.Write(data[:n]) - return err + return w.Write(data[:n]) case proto.Marshaler: // this path performs extra allocations data, err := t.Marshal() if err != nil { - return err + return 0, err } - _, err = w.Write(data) - return err + return w.Write(data) default: - return errNotMarshalable{reflect.TypeOf(obj)} + return 0, errNotMarshalable{reflect.TypeOf(obj)} } } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/types_proto.go b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/types_proto.go index a82227b23..27a2064c4 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/runtime/types_proto.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/runtime/types_proto.go @@ -18,6 +18,7 @@ package runtime import ( "fmt" + "io" ) type ProtobufMarshaller interface { @@ -28,6 +29,124 @@ type ProtobufReverseMarshaller interface { MarshalToSizedBuffer(data []byte) (int, error) } +const ( + typeMetaTag = 0xa + rawTag = 0x12 + contentEncodingTag = 0x1a + contentTypeTag = 0x22 + + // max length of a varint for a uint64 + maxUint64VarIntLength = 10 +) + +// MarshalToWriter allows a caller to provide a streaming writer for raw bytes, +// instead of populating them inside the Unknown struct. +// rawSize is the number of bytes rawWriter will write in a success case. +// writeRaw is called when it is time to write the raw bytes. It must return `rawSize, nil` or an error. +func (m *Unknown) MarshalToWriter(w io.Writer, rawSize int, writeRaw func(io.Writer) (int, error)) (int, error) { + size := 0 + + // reuse the buffer for varint marshaling + varintBuffer := make([]byte, maxUint64VarIntLength) + writeVarint := func(i int) (int, error) { + offset := encodeVarintGenerated(varintBuffer, len(varintBuffer), uint64(i)) + return w.Write(varintBuffer[offset:]) + } + + // TypeMeta + { + n, err := w.Write([]byte{typeMetaTag}) + size += n + if err != nil { + return size, err + } + + typeMetaBytes, err := m.TypeMeta.Marshal() + if err != nil { + return size, err + } + + n, err = writeVarint(len(typeMetaBytes)) + size += n + if err != nil { + return size, err + } + + n, err = w.Write(typeMetaBytes) + size += n + if err != nil { + return size, err + } + } + + // Raw, delegating write to writeRaw() + { + n, err := w.Write([]byte{rawTag}) + size += n + if err != nil { + return size, err + } + + n, err = writeVarint(rawSize) + size += n + if err != nil { + return size, err + } + + n, err = writeRaw(w) + size += n + if err != nil { + return size, err + } + if n != int(rawSize) { + return size, fmt.Errorf("the size value was %d, but encoding wrote %d bytes to data", rawSize, n) + } + } + + // ContentEncoding + { + n, err := w.Write([]byte{contentEncodingTag}) + size += n + if err != nil { + return size, err + } + + n, err = writeVarint(len(m.ContentEncoding)) + size += n + if err != nil { + return size, err + } + + n, err = w.Write([]byte(m.ContentEncoding)) + size += n + if err != nil { + return size, err + } + } + + // ContentEncoding + { + n, err := w.Write([]byte{contentTypeTag}) + size += n + if err != nil { + return size, err + } + + n, err = writeVarint(len(m.ContentType)) + size += n + if err != nil { + return size, err + } + + n, err = w.Write([]byte(m.ContentType)) + size += n + if err != nil { + return size, err + } + } + return size, nil +} + // NestedMarshalTo allows a caller to avoid extra allocations during serialization of an Unknown // that will contain an object that implements ProtobufMarshaller or ProtobufReverseMarshaller. func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64) (int, error) { @@ -43,12 +162,12 @@ func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64 copy(data[i:], m.ContentType) i = encodeVarintGenerated(data, i, uint64(len(m.ContentType))) i-- - data[i] = 0x22 + data[i] = contentTypeTag i -= len(m.ContentEncoding) copy(data[i:], m.ContentEncoding) i = encodeVarintGenerated(data, i, uint64(len(m.ContentEncoding))) i-- - data[i] = 0x1a + data[i] = contentEncodingTag if b != nil { if r, ok := b.(ProtobufReverseMarshaller); ok { n1, err := r.MarshalToSizedBuffer(data[:i]) @@ -75,7 +194,7 @@ func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64 } i = encodeVarintGenerated(data, i, size) i-- - data[i] = 0x12 + data[i] = rawTag } n2, err := m.TypeMeta.MarshalToSizedBuffer(data[:i]) if err != nil { @@ -84,6 +203,6 @@ func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64 i -= n2 i = encodeVarintGenerated(data, i, uint64(n2)) i-- - data[i] = 0xa + data[i] = typeMetaTag return msgSize - i, nil } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/types/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/types/doc.go index 5667fa992..783cbcdc8 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/types/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/types/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package types implements various generic types used throughout kubernetes. -package types // import "k8s.io/apimachinery/pkg/types" +package types diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go index fc0301844..38b666ef5 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/diff/diff.go @@ -23,7 +23,7 @@ import ( "strings" "text/tabwriter" - "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp" //nolint:depguard "k8s.io/apimachinery/pkg/util/dump" ) diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go index 5d4d6250a..b3b39bc38 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package errors implements various utility functions and types around errors. -package errors // import "k8s.io/apimachinery/pkg/util/errors" +package errors diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go index 1ab8fd396..f18845a41 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go @@ -91,12 +91,12 @@ func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) { } n, err := io.ReadAtLeast(r.r, data[:max], int(max)) r.remaining -= n - if err == io.ErrShortBuffer || r.remaining > 0 { - return n, io.ErrShortBuffer - } if err != nil { return n, err } + if r.remaining > 0 { + return n, io.ErrShortBuffer + } if n != expect { return n, io.ErrUnexpectedEOF } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go index 5893df5bd..1da83f14b 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package httpstream adds multiplexed streaming support to HTTP requests and // responses via connection upgrades. -package httpstream // import "k8s.io/apimachinery/pkg/util/httpstream" +package httpstream diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go index 3dd6f828b..a57e8df60 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go @@ -66,4 +66,4 @@ limitations under the License. // WRITE []byte{0, 102, 111, 111, 10} # send "foo\n" on channel 0 (STDIN) // WRITE []byte{255, 0} # send CLOSE signal (STDIN) // CLOSE -package wsstream // import "k8s.io/apimachinery/pkg/util/httpstream/wsstream" +package wsstream diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go index a502b5adb..2d6f6a0cc 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go @@ -20,24 +20,24 @@ limitations under the License. package intstr import ( - fuzz "github.com/google/gofuzz" + "sigs.k8s.io/randfill" ) -// Fuzz satisfies fuzz.Interface -func (intstr *IntOrString) Fuzz(c fuzz.Continue) { +// RandFill satisfies randfill.NativeSelfFiller +func (intstr *IntOrString) RandFill(c randfill.Continue) { if intstr == nil { return } - if c.RandBool() { + if c.Bool() { intstr.Type = Int - c.Fuzz(&intstr.IntVal) + c.Fill(&intstr.IntVal) intstr.StrVal = "" } else { intstr.Type = String intstr.IntVal = 0 - c.Fuzz(&intstr.StrVal) + c.Fill(&intstr.StrVal) } } // ensure IntOrString implements fuzz.Interface -var _ fuzz.Interface = &IntOrString{} +var _ randfill.NativeSelfFiller = &IntOrString{} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go index d14ecfad5..ea710f6b1 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package proxy provides transport and upgrade support for proxies. -package proxy // import "k8s.io/apimachinery/pkg/util/proxy" +package proxy diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go index df374949d..de97deae0 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go @@ -36,6 +36,11 @@ var ( ) // PanicHandlers is a list of functions which will be invoked when a panic happens. +// +// The code invoking these handlers prepares a contextual logger so that +// klog.FromContext(ctx) already skips over the panic handler itself and +// several other intermediate functions, ideally such that the log output +// is attributed to the code which triggered the panic. var PanicHandlers = []func(context.Context, interface{}){logPanic} // HandleCrash simply catches a crash and logs an error. Meant to be called via @@ -45,7 +50,7 @@ var PanicHandlers = []func(context.Context, interface{}){logPanic} // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // -// Contextual logging: HandleCrashWithContext should be used instead of HandleCrash in code which supports contextual logging. +// Contextual logging: HandleCrashWithContext or HandleCrashWithLogger should be used instead of HandleCrash in code which supports contextual logging. func HandleCrash(additionalHandlers ...func(interface{})) { if r := recover(); r != nil { additionalHandlersWithContext := make([]func(context.Context, interface{}), len(additionalHandlers)) @@ -74,10 +79,30 @@ func HandleCrashWithContext(ctx context.Context, additionalHandlers ...func(cont } } -// handleCrash is the common implementation of HandleCrash and HandleCrash. +// HandleCrashWithLogger simply catches a crash and logs an error. Meant to be called via +// defer. Additional context-specific handlers can be provided, and will be +// called in case of panic. HandleCrash actually crashes, after calling the +// handlers and logging the panic message. +// +// E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. +func HandleCrashWithLogger(logger klog.Logger, additionalHandlers ...func(context.Context, interface{})) { + if r := recover(); r != nil { + ctx := klog.NewContext(context.Background(), logger) + handleCrash(ctx, r, additionalHandlers...) + } +} + +// handleCrash is the common implementation of the HandleCrash* variants. // Having those call a common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleCrash(ctx context.Context, r any, additionalHandlers ...func(context.Context, interface{})) { + // We don't really know how many call frames to skip because the Go + // panic handler is between us and the code where the panic occurred. + // If it's one function (as in Go 1.21), then skipping four levels + // gets us to the function which called the `defer HandleCrashWithontext(...)`. + logger := klog.FromContext(ctx).WithCallDepth(4) + ctx = klog.NewContext(ctx, logger) + for _, fn := range PanicHandlers { fn(ctx, r) } @@ -106,11 +131,7 @@ func logPanic(ctx context.Context, r interface{}) { stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] - // We don't really know how many call frames to skip because the Go - // panic handler is between us and the code where the panic occurred. - // If it's one function (as in Go 1.21), then skipping four levels - // gets us to the function which called the `defer HandleCrashWithontext(...)`. - logger := klog.FromContext(ctx).WithCallDepth(4) + logger := klog.FromContext(ctx) // For backwards compatibility, conversion to string // is handled here instead of defering to the logging @@ -176,12 +197,19 @@ func HandleError(err error) { // and key/value pairs. // // This variant should be used instead of HandleError because it supports -// structured, contextual logging. +// structured, contextual logging. Alternatively, [HandleErrorWithLogger] can +// be used if a logger is available instead of a context. func HandleErrorWithContext(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { handleError(ctx, err, msg, keysAndValues...) } -// handleError is the common implementation of HandleError and HandleErrorWithContext. +// HandleErrorWithLogger is an alternative to [HandlerErrorWithContext] which accepts +// a logger for contextual logging. +func HandleErrorWithLogger(logger klog.Logger, err error, msg string, keysAndValues ...interface{}) { + handleError(klog.NewContext(context.Background(), logger), err, msg, keysAndValues...) +} + +// handleError is the common implementation of the HandleError* variants. // Using this common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleError(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go index fd281bdb8..194883390 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/sets/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package sets has generic set and specified sets. Generic set will // replace specified ones over time. And specific ones are deprecated. -package sets // import "k8s.io/apimachinery/pkg/util/sets" +package sets diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go new file mode 100644 index 000000000..1d15deae8 --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/error_matcher.go @@ -0,0 +1,212 @@ +/* +Copyright 2025 The Kubernetes 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 field + +import ( + "fmt" + "reflect" + "regexp" + "strings" +) + +// ErrorMatcher is a helper for comparing Error objects. +type ErrorMatcher struct { + // TODO(thockin): consider whether type is ever NOT required, maybe just + // assume it. + matchType bool + // TODO(thockin): consider whether field could be assumed - if the + // "want" error has a nil field, don't match on field. + matchField bool + // TODO(thockin): consider whether value could be assumed - if the + // "want" error has a nil value, don't match on field. + matchValue bool + matchOrigin bool + matchDetail func(want, got string) bool + requireOriginWhenInvalid bool +} + +// Matches returns true if the two Error objects match according to the +// configured criteria. +func (m ErrorMatcher) Matches(want, got *Error) bool { + if m.matchType && want.Type != got.Type { + return false + } + if m.matchField && want.Field != got.Field { + return false + } + if m.matchValue && !reflect.DeepEqual(want.BadValue, got.BadValue) { + return false + } + if m.matchOrigin { + if want.Origin != got.Origin { + return false + } + if m.requireOriginWhenInvalid && want.Type == ErrorTypeInvalid { + if want.Origin == "" || got.Origin == "" { + return false + } + } + } + if m.matchDetail != nil && !m.matchDetail(want.Detail, got.Detail) { + return false + } + return true +} + +// Render returns a string representation of the specified Error object, +// according to the criteria configured in the ErrorMatcher. +func (m ErrorMatcher) Render(e *Error) string { + buf := strings.Builder{} + + comma := func() { + if buf.Len() > 0 { + buf.WriteString(", ") + } + } + + if m.matchType { + comma() + buf.WriteString(fmt.Sprintf("Type=%q", e.Type)) + } + if m.matchField { + comma() + buf.WriteString(fmt.Sprintf("Field=%q", e.Field)) + } + if m.matchValue { + comma() + buf.WriteString(fmt.Sprintf("Value=%v", e.BadValue)) + } + if m.matchOrigin || m.requireOriginWhenInvalid && e.Type == ErrorTypeInvalid { + comma() + buf.WriteString(fmt.Sprintf("Origin=%q", e.Origin)) + } + if m.matchDetail != nil { + comma() + buf.WriteString(fmt.Sprintf("Detail=%q", e.Detail)) + } + return "{" + buf.String() + "}" +} + +// Exactly returns a derived ErrorMatcher which matches all fields exactly. +func (m ErrorMatcher) Exactly() ErrorMatcher { + return m.ByType().ByField().ByValue().ByOrigin().ByDetailExact() +} + +// ByType returns a derived ErrorMatcher which also matches by type. +func (m ErrorMatcher) ByType() ErrorMatcher { + m.matchType = true + return m +} + +// ByField returns a derived ErrorMatcher which also matches by field path. +func (m ErrorMatcher) ByField() ErrorMatcher { + m.matchField = true + return m +} + +// ByValue returns a derived ErrorMatcher which also matches by the errant +// value. +func (m ErrorMatcher) ByValue() ErrorMatcher { + m.matchValue = true + return m +} + +// ByOrigin returns a derived ErrorMatcher which also matches by the origin. +func (m ErrorMatcher) ByOrigin() ErrorMatcher { + m.matchOrigin = true + return m +} + +// RequireOriginWhenInvalid returns a derived ErrorMatcher which also requires +// the Origin field to be set when the Type is Invalid and the matcher is +// matching by Origin. +func (m ErrorMatcher) RequireOriginWhenInvalid() ErrorMatcher { + m.requireOriginWhenInvalid = true + return m +} + +// ByDetailExact returns a derived ErrorMatcher which also matches errors by +// the exact detail string. +func (m ErrorMatcher) ByDetailExact() ErrorMatcher { + m.matchDetail = func(want, got string) bool { + return got == want + } + return m +} + +// ByDetailSubstring returns a derived ErrorMatcher which also matches errors +// by a substring of the detail string. +func (m ErrorMatcher) ByDetailSubstring() ErrorMatcher { + m.matchDetail = func(want, got string) bool { + return strings.Contains(got, want) + } + return m +} + +// ByDetailRegexp returns a derived ErrorMatcher which also matches errors by a +// regular expression of the detail string, where the "want" string is assumed +// to be a valid regular expression. +func (m ErrorMatcher) ByDetailRegexp() ErrorMatcher { + m.matchDetail = func(want, got string) bool { + return regexp.MustCompile(want).MatchString(got) + } + return m +} + +// TestIntf lets users pass a testing.T while not coupling this package to Go's +// testing package. +type TestIntf interface { + Helper() + Errorf(format string, args ...any) + Logf(format string, args ...any) +} + +// Test compares two ErrorLists by the criteria configured in this matcher, and +// fails the test if they don't match. If a given "want" error matches multiple +// "got" errors, they will all be consumed. This might be OK (e.g. if there are +// multiple errors on the same field from the same origin) or it might be an +// insufficiently specific matcher, so these will be logged. +func (m ErrorMatcher) Test(tb TestIntf, want, got ErrorList) { + tb.Helper() + + remaining := got + for _, w := range want { + tmp := make(ErrorList, 0, len(remaining)) + n := 0 + for _, g := range remaining { + if m.Matches(w, g) { + n++ + } else { + tmp = append(tmp, g) + } + } + if n == 0 { + tb.Errorf("expected an error matching:\n%s", m.Render(w)) + } else if n > 1 { + // This is not necessarily and error, but it's worth logging in + // case it's not what the test author intended. + tb.Logf("multiple errors matched:\n%s", m.Render(w)) + } + remaining = tmp + } + if len(remaining) > 0 { + for _, e := range remaining { + exactly := m.Exactly() // makes a copy + tb.Errorf("unmatched error:\n%s", exactly.Render(e)) + } + } +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go index f1634bc0d..840d645ee 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go @@ -33,13 +33,35 @@ type Error struct { Field string BadValue interface{} Detail string + + // Origin uniquely identifies where this error was generated from. It is used in testing to + // compare expected errors against actual errors without relying on exact detail string matching. + // This allows tests to verify the correct validation logic triggered the error + // regardless of how the error message might be formatted or localized. + // + // The value should be either: + // - A simple camelCase identifier (e.g., "maximum", "maxItems") + // - A structured format using "format=" for validation errors related to specific formats + // (e.g., "format=dns-label", "format=qualified-name") + // + // If the Origin corresponds to an existing declarative validation tag or JSON Schema keyword, + // use that same name for consistency. + // + // Origin should be set in the most deeply nested validation function that + // can still identify the unique source of the error. + Origin string + + // CoveredByDeclarative is true when this error is covered by declarative + // validation. This field is to identify errors from imperative validation + // that should also be caught by declarative validation. + CoveredByDeclarative bool } var _ error = &Error{} // Error implements the error interface. -func (v *Error) Error() string { - return fmt.Sprintf("%s: %s", v.Field, v.ErrorBody()) +func (e *Error) Error() string { + return fmt.Sprintf("%s: %s", e.Field, e.ErrorBody()) } type OmitValueType struct{} @@ -48,21 +70,21 @@ var omitValue = OmitValueType{} // ErrorBody returns the error message without the field name. This is useful // for building nice-looking higher-level error reporting. -func (v *Error) ErrorBody() string { +func (e *Error) ErrorBody() string { var s string switch { - case v.Type == ErrorTypeRequired: - s = v.Type.String() - case v.Type == ErrorTypeForbidden: - s = v.Type.String() - case v.Type == ErrorTypeTooLong: - s = v.Type.String() - case v.Type == ErrorTypeInternal: - s = v.Type.String() - case v.BadValue == omitValue: - s = v.Type.String() + case e.Type == ErrorTypeRequired: + s = e.Type.String() + case e.Type == ErrorTypeForbidden: + s = e.Type.String() + case e.Type == ErrorTypeTooLong: + s = e.Type.String() + case e.Type == ErrorTypeInternal: + s = e.Type.String() + case e.BadValue == omitValue: + s = e.Type.String() default: - value := v.BadValue + value := e.BadValue valueType := reflect.TypeOf(value) if value == nil || valueType == nil { value = "null" @@ -76,26 +98,38 @@ func (v *Error) ErrorBody() string { switch t := value.(type) { case int64, int32, float64, float32, bool: // use simple printer for simple types - s = fmt.Sprintf("%s: %v", v.Type, value) + s = fmt.Sprintf("%s: %v", e.Type, value) case string: - s = fmt.Sprintf("%s: %q", v.Type, t) + s = fmt.Sprintf("%s: %q", e.Type, t) case fmt.Stringer: // anything that defines String() is better than raw struct - s = fmt.Sprintf("%s: %s", v.Type, t.String()) + s = fmt.Sprintf("%s: %s", e.Type, t.String()) default: // fallback to raw struct // TODO: internal types have panic guards against json.Marshalling to prevent // accidental use of internal types in external serialized form. For now, use // %#v, although it would be better to show a more expressive output in the future - s = fmt.Sprintf("%s: %#v", v.Type, value) + s = fmt.Sprintf("%s: %#v", e.Type, value) } } - if len(v.Detail) != 0 { - s += fmt.Sprintf(": %s", v.Detail) + if len(e.Detail) != 0 { + s += fmt.Sprintf(": %s", e.Detail) } return s } +// WithOrigin adds origin information to the FieldError +func (e *Error) WithOrigin(o string) *Error { + e.Origin = o + return e +} + +// MarkCoveredByDeclarative marks the error as covered by declarative validation. +func (e *Error) MarkCoveredByDeclarative() *Error { + e.CoveredByDeclarative = true + return e +} + // ErrorType is a machine readable value providing more detail about why // a field is invalid. These values are expected to match 1-1 with // CauseType in api/types.go. @@ -169,32 +203,32 @@ func (t ErrorType) String() string { // TypeInvalid returns a *Error indicating "type is invalid" func TypeInvalid(field *Path, value interface{}, detail string) *Error { - return &Error{ErrorTypeTypeInvalid, field.String(), value, detail} + return &Error{ErrorTypeTypeInvalid, field.String(), value, detail, "", false} } // NotFound returns a *Error indicating "value not found". This is // used to report failure to find a requested value (e.g. looking up an ID). func NotFound(field *Path, value interface{}) *Error { - return &Error{ErrorTypeNotFound, field.String(), value, ""} + return &Error{ErrorTypeNotFound, field.String(), value, "", "", false} } // Required returns a *Error indicating "value required". This is used // to report required values that are not provided (e.g. empty strings, null // values, or empty arrays). func Required(field *Path, detail string) *Error { - return &Error{ErrorTypeRequired, field.String(), "", detail} + return &Error{ErrorTypeRequired, field.String(), "", detail, "", false} } // Duplicate returns a *Error indicating "duplicate value". This is // used to report collisions of values that must be unique (e.g. names or IDs). func Duplicate(field *Path, value interface{}) *Error { - return &Error{ErrorTypeDuplicate, field.String(), value, ""} + return &Error{ErrorTypeDuplicate, field.String(), value, "", "", false} } // Invalid returns a *Error indicating "invalid value". This is used // to report malformed values (e.g. failed regex match, too long, out of bounds). func Invalid(field *Path, value interface{}, detail string) *Error { - return &Error{ErrorTypeInvalid, field.String(), value, detail} + return &Error{ErrorTypeInvalid, field.String(), value, detail, "", false} } // NotSupported returns a *Error indicating "unsupported value". @@ -209,7 +243,7 @@ func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *E } detail = "supported values: " + strings.Join(quotedValues, ", ") } - return &Error{ErrorTypeNotSupported, field.String(), value, detail} + return &Error{ErrorTypeNotSupported, field.String(), value, detail, "", false} } // Forbidden returns a *Error indicating "forbidden". This is used to @@ -217,7 +251,7 @@ func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *E // some conditions, but which are not permitted by current conditions (e.g. // security policy). func Forbidden(field *Path, detail string) *Error { - return &Error{ErrorTypeForbidden, field.String(), "", detail} + return &Error{ErrorTypeForbidden, field.String(), "", detail, "", false} } // TooLong returns a *Error indicating "too long". This is used to report that @@ -231,7 +265,7 @@ func TooLong(field *Path, value interface{}, maxLength int) *Error { } else { msg = "value is too long" } - return &Error{ErrorTypeTooLong, field.String(), "", msg} + return &Error{ErrorTypeTooLong, field.String(), "", msg, "", false} } // TooLongMaxLength returns a *Error indicating "too long". @@ -259,14 +293,14 @@ func TooMany(field *Path, actualQuantity, maxQuantity int) *Error { actual = omitValue } - return &Error{ErrorTypeTooMany, field.String(), actual, msg} + return &Error{ErrorTypeTooMany, field.String(), actual, msg, "", false} } // InternalError returns a *Error indicating "internal error". This is used // to signal that an error was found that was not directly related to user // input. The err argument must be non-nil. func InternalError(field *Path, err error) *Error { - return &Error{ErrorTypeInternal, field.String(), nil, err.Error()} + return &Error{ErrorTypeInternal, field.String(), nil, err.Error(), "", false} } // ErrorList holds a set of Errors. It is plausible that we might one day have @@ -285,6 +319,22 @@ func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher { } } +// WithOrigin sets the origin for all errors in the list and returns the updated list. +func (list ErrorList) WithOrigin(origin string) ErrorList { + for _, err := range list { + err.Origin = origin + } + return list +} + +// MarkCoveredByDeclarative marks all errors in the list as covered by declarative validation. +func (list ErrorList) MarkCoveredByDeclarative() ErrorList { + for _, err := range list { + err.CoveredByDeclarative = true + } + return list +} + // ToAggregate converts the ErrorList into an errors.Aggregate. func (list ErrorList) ToAggregate() utilerrors.Aggregate { if len(list) == 0 { @@ -321,3 +371,25 @@ func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList { // FilterOut takes an Aggregate and returns an Aggregate return fromAggregate(err.(utilerrors.Aggregate)) } + +// ExtractCoveredByDeclarative returns a new ErrorList containing only the errors that should be covered by declarative validation. +func (list ErrorList) ExtractCoveredByDeclarative() ErrorList { + newList := ErrorList{} + for _, err := range list { + if err.CoveredByDeclarative { + newList = append(newList, err) + } + } + return newList +} + +// RemoveCoveredByDeclarative returns a new ErrorList containing only the errors that should not be covered by declarative validation. +func (list ErrorList) RemoveCoveredByDeclarative() ErrorList { + newList := ErrorList{} + for _, err := range list { + if !err.CoveredByDeclarative { + newList = append(newList, err) + } + } + return newList +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go new file mode 100644 index 000000000..6e947c74c --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/ip.go @@ -0,0 +1,278 @@ +/* +Copyright 2023 The Kubernetes 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 validation + +import ( + "fmt" + "net" + "net/netip" + "slices" + + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/klog/v2" + netutils "k8s.io/utils/net" +) + +func parseIP(fldPath *field.Path, value string, strictValidation bool) (net.IP, field.ErrorList) { + var allErrors field.ErrorList + + ip := netutils.ParseIPSloppy(value) + if ip == nil { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)")) + return nil, allErrors + } + + if strictValidation { + addr, err := netip.ParseAddr(value) + if err != nil { + // If netutils.ParseIPSloppy parsed it, but netip.ParseAddr + // doesn't, then it must have illegal leading 0s. + allErrors = append(allErrors, field.Invalid(fldPath, value, "must not have leading 0s")) + } + if addr.Is4In6() { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must not be an IPv4-mapped IPv6 address")) + } + } + + return ip, allErrors +} + +// IsValidIPForLegacyField tests that the argument is a valid IP address for a "legacy" +// API field that predates strict IP validation. In particular, this allows IPs that are +// not in canonical form (e.g., "FE80:0:0:0:0:0:0:0abc" instead of "fe80::abc"). +// +// If strictValidation is false, this also allows IPs in certain invalid or ambiguous +// formats: +// +// 1. IPv4 IPs are allowed to have leading "0"s in octets (e.g. "010.002.003.004"). +// Historically, net.ParseIP (and later netutils.ParseIPSloppy) simply ignored leading +// "0"s in IPv4 addresses, but most libc-based software treats 0-prefixed IPv4 octets +// as octal, meaning different software might interpret the same string as two +// different IPs, potentially leading to security issues. (Current net.ParseIP and +// netip.ParseAddr simply reject inputs with leading "0"s.) +// +// 2. IPv4-mapped IPv6 IPs (e.g. "::ffff:1.2.3.4") are allowed. These can also lead to +// different software interpreting the value in different ways, because they may be +// treated as IPv4 by some software and IPv6 by other software. (net.ParseIP and +// netip.ParseAddr both allow these, but there are no use cases for representing IPv4 +// addresses as IPv4-mapped IPv6 addresses in Kubernetes.) +// +// Alternatively, when validating an update to an existing field, you can pass a list of +// IP values from the old object that should be accepted if they appear in the new object +// even if they are not valid. +// +// This function should only be used to validate the existing fields that were +// historically validated in this way, and strictValidation should be true unless the +// StrictIPCIDRValidation feature gate is disabled. Use IsValidIP for parsing new fields. +func IsValidIPForLegacyField(fldPath *field.Path, value string, strictValidation bool, validOldIPs []string) field.ErrorList { + if slices.Contains(validOldIPs, value) { + return nil + } + _, allErrors := parseIP(fldPath, value, strictValidation) + return allErrors.WithOrigin("format=ip-sloppy") +} + +// IsValidIP tests that the argument is a valid IP address, according to current +// Kubernetes standards for IP address validation. +func IsValidIP(fldPath *field.Path, value string) field.ErrorList { + ip, allErrors := parseIP(fldPath, value, true) + if len(allErrors) != 0 { + return allErrors.WithOrigin("format=ip-strict") + } + + if value != ip.String() { + allErrors = append(allErrors, field.Invalid(fldPath, value, fmt.Sprintf("must be in canonical form (%q)", ip.String()))) + } + return allErrors.WithOrigin("format=ip-strict") +} + +// GetWarningsForIP returns warnings for IP address values in non-standard forms. This +// should only be used with fields that are validated with IsValidIPForLegacyField(). +func GetWarningsForIP(fldPath *field.Path, value string) []string { + ip := netutils.ParseIPSloppy(value) + if ip == nil { + klog.ErrorS(nil, "GetWarningsForIP called on value that was not validated with IsValidIPForLegacyField", "field", fldPath, "value", value) + return nil + } + + addr, _ := netip.ParseAddr(value) + if !addr.IsValid() || addr.Is4In6() { + // This catches 2 cases: leading 0s (if ParseIPSloppy() accepted it but + // ParseAddr() doesn't) or IPv4-mapped IPv6 (.Is4In6()). Either way, + // re-stringifying the net.IP value will give the preferred form. + return []string{ + fmt.Sprintf("%s: non-standard IP address %q will be considered invalid in a future Kubernetes release: use %q", fldPath, value, ip.String()), + } + } + + // If ParseIPSloppy() and ParseAddr() both accept it then it's fully valid, though + // it may be non-canonical. + if addr.Is6() && addr.String() != value { + return []string{ + fmt.Sprintf("%s: IPv6 address %q should be in RFC 5952 canonical format (%q)", fldPath, value, addr.String()), + } + } + + return nil +} + +func parseCIDR(fldPath *field.Path, value string, strictValidation bool) (*net.IPNet, field.ErrorList) { + var allErrors field.ErrorList + + _, ipnet, err := netutils.ParseCIDRSloppy(value) + if err != nil { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid CIDR value, (e.g. 10.9.8.0/24 or 2001:db8::/64)")) + return nil, allErrors + } + + if strictValidation { + prefix, err := netip.ParsePrefix(value) + if err != nil { + // If netutils.ParseCIDRSloppy parsed it, but netip.ParsePrefix + // doesn't, then it must have illegal leading 0s (either in the + // IP part or the prefix). + allErrors = append(allErrors, field.Invalid(fldPath, value, "must not have leading 0s in IP or prefix length")) + } else if prefix.Addr().Is4In6() { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must not have an IPv4-mapped IPv6 address")) + } else if prefix.Addr() != prefix.Masked().Addr() { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must not have bits set beyond the prefix length")) + } + } + + return ipnet, allErrors +} + +// IsValidCIDRForLegacyField tests that the argument is a valid CIDR value for a "legacy" +// API field that predates strict IP validation. In particular, this allows IPs that are +// not in canonical form (e.g., "FE80:0abc:0:0:0:0:0:0/64" instead of "fe80:abc::/64"). +// +// If strictValidation is false, this also allows CIDR values in certain invalid or +// ambiguous formats: +// +// 1. The IP part of the CIDR value is parsed as with IsValidIPForLegacyField with +// strictValidation=false. +// +// 2. The CIDR value is allowed to be either a "subnet"/"mask" (with the lower bits after +// the prefix length all being 0), or an "interface address" as with `ip addr` (with a +// complete IP address and associated subnet length). With strict validation, the +// value is required to be in "subnet"/"mask" form. +// +// 3. The prefix length is allowed to have leading 0s. +// +// Alternatively, when validating an update to an existing field, you can pass a list of +// CIDR values from the old object that should be accepted if they appear in the new +// object even if they are not valid. +// +// This function should only be used to validate the existing fields that were +// historically validated in this way, and strictValidation should be true unless the +// StrictIPCIDRValidation feature gate is disabled. Use IsValidCIDR or +// IsValidInterfaceAddress for parsing new fields. +func IsValidCIDRForLegacyField(fldPath *field.Path, value string, strictValidation bool, validOldCIDRs []string) field.ErrorList { + if slices.Contains(validOldCIDRs, value) { + return nil + } + + _, allErrors := parseCIDR(fldPath, value, strictValidation) + return allErrors +} + +// IsValidCIDR tests that the argument is a valid CIDR value, according to current +// Kubernetes standards for CIDR validation. This function is only for +// "subnet"/"mask"-style CIDR values (e.g., "192.168.1.0/24", with no bits set beyond the +// prefix length). Use IsValidInterfaceAddress for "ifaddr"-style CIDR values. +func IsValidCIDR(fldPath *field.Path, value string) field.ErrorList { + ipnet, allErrors := parseCIDR(fldPath, value, true) + if len(allErrors) != 0 { + return allErrors + } + + if value != ipnet.String() { + allErrors = append(allErrors, field.Invalid(fldPath, value, fmt.Sprintf("must be in canonical form (%q)", ipnet.String()))) + } + return allErrors +} + +// GetWarningsForCIDR returns warnings for CIDR values in non-standard forms. This should +// only be used with fields that are validated with IsValidCIDRForLegacyField(). +func GetWarningsForCIDR(fldPath *field.Path, value string) []string { + ip, ipnet, err := netutils.ParseCIDRSloppy(value) + if err != nil { + klog.ErrorS(err, "GetWarningsForCIDR called on value that was not validated with IsValidCIDRForLegacyField", "field", fldPath, "value", value) + return nil + } + + var warnings []string + + // Check for bits set after prefix length + if !ip.Equal(ipnet.IP) { + _, addrlen := ipnet.Mask.Size() + singleIPCIDR := fmt.Sprintf("%s/%d", ip.String(), addrlen) + warnings = append(warnings, + fmt.Sprintf("%s: CIDR value %q is ambiguous in this context (should be %q or %q?)", fldPath, value, ipnet.String(), singleIPCIDR), + ) + } + + prefix, _ := netip.ParsePrefix(value) + addr := prefix.Addr() + if !prefix.IsValid() || addr.Is4In6() { + // This catches 2 cases: leading 0s (if ParseCIDRSloppy() accepted it but + // ParsePrefix() doesn't) or IPv4-mapped IPv6 (.Is4In6()). Either way, + // re-stringifying the net.IPNet value will give the preferred form. + warnings = append(warnings, + fmt.Sprintf("%s: non-standard CIDR value %q will be considered invalid in a future Kubernetes release: use %q", fldPath, value, ipnet.String()), + ) + } + + // If ParseCIDRSloppy() and ParsePrefix() both accept it then it's fully valid, + // though it may be non-canonical. But only check this if there are no other + // warnings, since either of the other warnings would also cause a round-trip + // failure. + if len(warnings) == 0 && addr.Is6() && prefix.String() != value { + warnings = append(warnings, + fmt.Sprintf("%s: IPv6 CIDR value %q should be in RFC 5952 canonical format (%q)", fldPath, value, prefix.String()), + ) + } + + return warnings +} + +// IsValidInterfaceAddress tests that the argument is a valid "ifaddr"-style CIDR value in +// canonical form (e.g., "192.168.1.5/24", with a complete IP address and associated +// subnet length). Use IsValidCIDR for "subnet"/"mask"-style CIDR values (e.g., +// "192.168.1.0/24"). +func IsValidInterfaceAddress(fldPath *field.Path, value string) field.ErrorList { + var allErrors field.ErrorList + ip, ipnet, err := netutils.ParseCIDRSloppy(value) + if err != nil { + allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid address in CIDR form, (e.g. 10.9.8.7/24 or 2001:db8::1/64)")) + return allErrors + } + + // The canonical form of `value` is not `ipnet.String()`, because `ipnet` doesn't + // include the bits after the prefix. We need to construct the canonical form + // ourselves from `ip` and `ipnet.Mask`. + maskSize, _ := ipnet.Mask.Size() + if netutils.IsIPv4(ip) && maskSize > net.IPv4len*8 { + // "::ffff:192.168.0.1/120" -> "192.168.0.1/24" + maskSize -= (net.IPv6len - net.IPv4len) * 8 + } + canonical := fmt.Sprintf("%s/%d", ip.String(), maskSize) + if value != canonical { + allErrors = append(allErrors, field.Invalid(fldPath, value, fmt.Sprintf("must be in canonical form (%q)", canonical))) + } + return allErrors +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go index 9bc393cf5..b6be7af1b 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go @@ -24,7 +24,6 @@ import ( "unicode" "k8s.io/apimachinery/pkg/util/validation/field" - netutils "k8s.io/utils/net" ) const qnameCharFmt string = "[A-Za-z0-9]" @@ -369,45 +368,6 @@ func IsValidPortName(port string) []string { return errs } -// IsValidIP tests that the argument is a valid IP address. -func IsValidIP(fldPath *field.Path, value string) field.ErrorList { - var allErrors field.ErrorList - if netutils.ParseIPSloppy(value) == nil { - allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)")) - } - return allErrors -} - -// IsValidIPv4Address tests that the argument is a valid IPv4 address. -func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList { - var allErrors field.ErrorList - ip := netutils.ParseIPSloppy(value) - if ip == nil || ip.To4() == nil { - allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv4 address")) - } - return allErrors -} - -// IsValidIPv6Address tests that the argument is a valid IPv6 address. -func IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList { - var allErrors field.ErrorList - ip := netutils.ParseIPSloppy(value) - if ip == nil || ip.To4() != nil { - allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv6 address")) - } - return allErrors -} - -// IsValidCIDR tests that the argument is a valid CIDR value. -func IsValidCIDR(fldPath *field.Path, value string) field.ErrorList { - var allErrors field.ErrorList - _, _, err := netutils.ParseCIDRSloppy(value) - if err != nil { - allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid CIDR value, (e.g. 10.9.8.0/24 or 2001:db8::/64)")) - } - return allErrors -} - const percentFmt string = "[0-9]+%" const percentErrMsg string = "a valid percent string must be a numeric string followed by an ending '%'" diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/version/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/version/doc.go index 5b2b22b6d..da88813da 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/version/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/version/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package version provides utilities for version number comparisons -package version // import "k8s.io/apimachinery/pkg/util/version" +package version diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/version/version.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/version/version.go index b7812ff2d..72c0769e6 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/version/version.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/version/version.go @@ -33,7 +33,6 @@ type Version struct { semver bool preRelease string buildMetadata string - info apimachineryversion.Info } var ( @@ -456,27 +455,28 @@ func (v *Version) Compare(other string) (int, error) { return v.compareInternal(ov), nil } -// WithInfo returns copy of the version object with requested info +// WithInfo returns copy of the version object. +// Deprecated: The Info field has been removed from the Version struct. This method no longer modifies the Version object. func (v *Version) WithInfo(info apimachineryversion.Info) *Version { result := *v - result.info = info return &result } +// Info returns the version information of a component. +// Deprecated: Use Info() from effective version instead. func (v *Version) Info() *apimachineryversion.Info { if v == nil { return nil } // in case info is empty, or the major and minor in info is different from the actual major and minor - v.info.Major = itoa(v.Major()) - v.info.Minor = itoa(v.Minor()) - if v.info.GitVersion == "" { - v.info.GitVersion = v.String() + return &apimachineryversion.Info{ + Major: Itoa(v.Major()), + Minor: Itoa(v.Minor()), + GitVersion: v.String(), } - return &v.info } -func itoa(i uint) string { +func Itoa(i uint) string { if i == 0 { return "" } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go index 418761925..177be09a9 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/backoff.go @@ -157,6 +157,8 @@ func (b Backoff) DelayWithReset(c clock.Clock, resetInterval time.Duration) Dela // Until is syntactic sugar on top of JitterUntil with zero jitter factor and // with sliding = true (which means the timer for period starts after the f // completes). +// +// Contextual logging: UntilWithContext should be used instead of Until in code which supports contextual logging. func Until(f func(), period time.Duration, stopCh <-chan struct{}) { JitterUntil(f, period, 0.0, true, stopCh) } @@ -176,6 +178,8 @@ func UntilWithContext(ctx context.Context, f func(context.Context), period time. // NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter // factor, with sliding = false (meaning the timer for period starts at the same // time as the function starts). +// +// Contextual logging: NonSlidingUntilWithContext should be used instead of NonSlidingUntil in code which supports contextual logging. func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) { JitterUntil(f, period, 0.0, false, stopCh) } @@ -200,19 +204,44 @@ func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), pe // // Close stopCh to stop. f may not be invoked if stop channel is already // closed. Pass NeverStop to if you don't want it stop. +// +// Contextual logging: JitterUntilWithContext should be used instead of JitterUntil in code which supports contextual logging. func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) { BackoffUntil(f, NewJitteredBackoffManager(period, jitterFactor, &clock.RealClock{}), sliding, stopCh) } +// JitterUntilWithContext loops until context is done, running f every period. +// +// If jitterFactor is positive, the period is jittered before every run of f. +// If jitterFactor is not positive, the period is unchanged and not jittered. +// +// If sliding is true, the period is computed after f runs. If it is false then +// period includes the runtime for f. +// +// Cancel context to stop. f may not be invoked if context is already done. +func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) { + BackoffUntilWithContext(ctx, f, NewJitteredBackoffManager(period, jitterFactor, &clock.RealClock{}), sliding) +} + // BackoffUntil loops until stop channel is closed, run f every duration given by BackoffManager. // // If sliding is true, the period is computed after f runs. If it is false then // period includes the runtime for f. +// +// Contextual logging: BackoffUntilWithContext should be used instead of BackoffUntil in code which supports contextual logging. func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan struct{}) { + BackoffUntilWithContext(ContextForChannel(stopCh), func(context.Context) { f() }, backoff, sliding) +} + +// BackoffUntilWithContext loops until context is done, run f every duration given by BackoffManager. +// +// If sliding is true, the period is computed after f runs. If it is false then +// period includes the runtime for f. +func BackoffUntilWithContext(ctx context.Context, f func(ctx context.Context), backoff BackoffManager, sliding bool) { var t clock.Timer for { select { - case <-stopCh: + case <-ctx.Done(): return default: } @@ -222,8 +251,8 @@ func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan } func() { - defer runtime.HandleCrash() - f() + defer runtime.HandleCrashWithContext(ctx) + f(ctx) }() if sliding { @@ -236,7 +265,7 @@ func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan // In order to mitigate we re-check stopCh at the beginning // of every loop to prevent extra executions of f(). select { - case <-stopCh: + case <-ctx.Done(): if !t.Stop() { <-t.C() } @@ -246,19 +275,6 @@ func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan } } -// JitterUntilWithContext loops until context is done, running f every period. -// -// If jitterFactor is positive, the period is jittered before every run of f. -// If jitterFactor is not positive, the period is unchanged and not jittered. -// -// If sliding is true, the period is computed after f runs. If it is false then -// period includes the runtime for f. -// -// Cancel context to stop. f may not be invoked if context is already expired. -func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) { - JitterUntil(func() { f(ctx) }, period, jitterFactor, sliding, ctx.Done()) -} - // backoffManager provides simple backoff behavior in a threadsafe manner to a caller. type backoffManager struct { backoff Backoff diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go index 3f0c968ec..ff89dc170 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package wait provides tools for polling or listening for changes // to a condition. -package wait // import "k8s.io/apimachinery/pkg/util/wait" +package wait diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go index 107bfc132..9f9b929ff 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/loop.go @@ -49,7 +49,7 @@ func loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding // if we haven't requested immediate execution, delay once if immediate { if ok, err := func() (bool, error) { - defer runtime.HandleCrash() + defer runtime.HandleCrashWithContext(ctx) return condition(ctx) }(); err != nil || ok { return err @@ -83,7 +83,7 @@ func loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding t.Next() } if ok, err := func() (bool, error) { - defer runtime.HandleCrash() + defer runtime.HandleCrashWithContext(ctx) return condition(ctx) }(); err != nil || ok { return err diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go index 6805e8cf9..7379a8d5a 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/wait/wait.go @@ -80,6 +80,10 @@ func Forever(f func(), period time.Duration) { Until(f, period, NeverStop) } +// jitterRand is a dedicated random source for jitter calculations. +// It defaults to rand.Float64, but is a package variable so it can be overridden to make unit tests deterministic. +var jitterRand = rand.Float64 + // Jitter returns a time.Duration between duration and duration + maxFactor * // duration. // @@ -89,7 +93,7 @@ func Jitter(duration time.Duration, maxFactor float64) time.Duration { if maxFactor <= 0.0 { maxFactor = 1.0 } - wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration)) + wait := duration + time.Duration(jitterRand()*maxFactor*float64(duration)) return wait } @@ -141,6 +145,7 @@ func (c channelContext) Value(key any) any { return nil } // // Deprecated: Will be removed when the legacy polling methods are removed. func runConditionWithCrashProtection(condition ConditionFunc) (bool, error) { + //nolint:logcheck // Already deprecated. defer runtime.HandleCrash() return condition() } @@ -150,7 +155,7 @@ func runConditionWithCrashProtection(condition ConditionFunc) (bool, error) { // // Deprecated: Will be removed when the legacy polling methods are removed. func runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error) { - defer runtime.HandleCrash() + defer runtime.HandleCrashWithContext(ctx) return condition(ctx) } diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/waitgroup/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/waitgroup/doc.go index a6f29cd7c..6eb7903a7 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/waitgroup/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/waitgroup/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package waitgroup implements SafeWaitGroup wrap of sync.WaitGroup. // Add with positive delta when waiting will fail, to prevent sync.WaitGroup race issue. -package waitgroup // import "k8s.io/apimachinery/pkg/util/waitgroup" +package waitgroup diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go index 9837b3df2..7342f8d1e 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go @@ -20,10 +20,12 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "strings" "unicode" + "unicode/utf8" jsonutil "k8s.io/apimachinery/pkg/util/json" @@ -92,7 +94,7 @@ func UnmarshalStrict(data []byte, v interface{}) error { // YAML decoding path is not used (so that error messages are // JSON specific). func ToJSON(data []byte) ([]byte, error) { - if hasJSONPrefix(data) { + if IsJSONBuffer(data) { return data, nil } return yaml.YAMLToJSON(data) @@ -102,7 +104,8 @@ func ToJSON(data []byte) ([]byte, error) { // separating individual documents. It first converts the YAML // body to JSON, then unmarshals the JSON. type YAMLToJSONDecoder struct { - reader Reader + reader Reader + inputOffset int } // NewYAMLToJSONDecoder decodes YAML documents from the provided @@ -121,7 +124,7 @@ func NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder { // yaml.Unmarshal. func (d *YAMLToJSONDecoder) Decode(into interface{}) error { bytes, err := d.reader.Read() - if err != nil && err != io.EOF { + if err != nil && err != io.EOF { //nolint:errorlint return err } @@ -131,9 +134,14 @@ func (d *YAMLToJSONDecoder) Decode(into interface{}) error { return YAMLSyntaxError{err} } } + d.inputOffset += len(bytes) return err } +func (d *YAMLToJSONDecoder) InputOffset() int { + return d.inputOffset +} + // YAMLDecoder reads chunks of objects and returns ErrShortBuffer if // the data is not sufficient. type YAMLDecoder struct { @@ -229,18 +237,20 @@ func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err return 0, nil, nil } -// decoder is a convenience interface for Decode. -type decoder interface { - Decode(into interface{}) error -} - -// YAMLOrJSONDecoder attempts to decode a stream of JSON documents or -// YAML documents by sniffing for a leading { character. +// YAMLOrJSONDecoder attempts to decode a stream of JSON or YAML documents. +// While JSON is YAML, the way Go's JSON decode defines a multi-document stream +// is a series of JSON objects (e.g. {}{}), but YAML defines a multi-document +// stream as a series of documents separated by "---". +// +// This decoder will attempt to decode the stream as JSON first, and if that +// fails, it will switch to YAML. Once it determines the stream is JSON (by +// finding a non-YAML-delimited series of objects), it will not switch to YAML. +// Once it switches to YAML it will not switch back to JSON. type YAMLOrJSONDecoder struct { - r io.Reader - bufferSize int - - decoder decoder + json *json.Decoder + yaml *YAMLToJSONDecoder + stream *StreamReader + count int // how many objects have been decoded } type JSONSyntaxError struct { @@ -265,31 +275,108 @@ func (e YAMLSyntaxError) Error() string { // how far into the stream the decoder will look to figure out whether this // is a JSON stream (has whitespace followed by an open brace). func NewYAMLOrJSONDecoder(r io.Reader, bufferSize int) *YAMLOrJSONDecoder { - return &YAMLOrJSONDecoder{ - r: r, - bufferSize: bufferSize, + d := &YAMLOrJSONDecoder{} + + reader, _, mightBeJSON := GuessJSONStream(r, bufferSize) + d.stream = reader + if mightBeJSON { + d.json = json.NewDecoder(reader) + } else { + d.yaml = NewYAMLToJSONDecoder(reader) } + return d } // Decode unmarshals the next object from the underlying stream into the // provide object, or returns an error. func (d *YAMLOrJSONDecoder) Decode(into interface{}) error { - if d.decoder == nil { - buffer, _, isJSON := GuessJSONStream(d.r, d.bufferSize) - if isJSON { - d.decoder = json.NewDecoder(buffer) + // Because we don't know if this is a JSON or YAML stream, a failure from + // both decoders is ambiguous. When in doubt, it will return the error from + // the JSON decoder. Unfortunately, this means that if the first document + // is invalid YAML, the error won't be awesome. + // TODO: the errors from YAML are not great, we could improve them a lot. + var firstErr error + if d.json != nil { + err := d.json.Decode(into) + if err == nil { + d.stream.Consume(int(d.json.InputOffset()) - d.stream.Consumed()) + d.count++ + return nil + } + if err == io.EOF { //nolint:errorlint + return err + } + var syntax *json.SyntaxError + if ok := errors.As(err, &syntax); ok { + firstErr = JSONSyntaxError{ + Offset: syntax.Offset, + Err: syntax, + } } else { - d.decoder = NewYAMLToJSONDecoder(buffer) + firstErr = err + } + if d.count > 1 { + // If we found 0 or 1 JSON object(s), this stream is still + // ambiguous. But if we found more than 1 JSON object, then this + // is an unambiguous JSON stream, and we should not switch to YAML. + return err + } + // If JSON decoding hits the end of one object and then fails on the + // next, it leaves any leading whitespace in the buffer, which can + // confuse the YAML decoder. We just eat any whitespace we find, up to + // and including the first newline. + d.stream.Rewind() + if err := d.consumeWhitespace(); err == nil { + d.yaml = NewYAMLToJSONDecoder(d.stream) + } + d.json = nil + } + if d.yaml != nil { + err := d.yaml.Decode(into) + if err == nil { + d.stream.Consume(d.yaml.InputOffset() - d.stream.Consumed()) + d.count++ + return nil + } + if err == io.EOF { //nolint:errorlint + return err + } + if firstErr == nil { + firstErr = err } } - err := d.decoder.Decode(into) - if syntax, ok := err.(*json.SyntaxError); ok { - return JSONSyntaxError{ - Offset: syntax.Offset, - Err: syntax, + if firstErr != nil { + return firstErr + } + return fmt.Errorf("decoding failed as both JSON and YAML") +} + +func (d *YAMLOrJSONDecoder) consumeWhitespace() error { + consumed := 0 + for { + buf, err := d.stream.ReadN(4) + if err != nil && err == io.EOF { //nolint:errorlint + return err + } + r, sz := utf8.DecodeRune(buf) + if r == utf8.RuneError || sz == 0 { + return fmt.Errorf("invalid utf8 rune") + } + d.stream.RewindN(len(buf) - sz) + if !unicode.IsSpace(r) { + d.stream.RewindN(sz) + d.stream.Consume(consumed) + return nil + } + if r == '\n' { + d.stream.Consume(consumed) + return nil + } + if err == io.EOF { //nolint:errorlint + break } } - return err + return io.EOF } type Reader interface { @@ -311,7 +398,7 @@ func (r *YAMLReader) Read() ([]byte, error) { var buffer bytes.Buffer for { line, err := r.reader.Read() - if err != nil && err != io.EOF { + if err != nil && err != io.EOF { //nolint:errorlint return nil, err } @@ -329,11 +416,11 @@ func (r *YAMLReader) Read() ([]byte, error) { if buffer.Len() != 0 { return buffer.Bytes(), nil } - if err == io.EOF { + if err == io.EOF { //nolint:errorlint return nil, err } } - if err == io.EOF { + if err == io.EOF { //nolint:errorlint if buffer.Len() != 0 { // If we're at EOF, we have a final, non-terminated line. Return it. return buffer.Bytes(), nil @@ -369,26 +456,20 @@ func (r *LineReader) Read() ([]byte, error) { // GuessJSONStream scans the provided reader up to size, looking // for an open brace indicating this is JSON. It will return the // bufio.Reader it creates for the consumer. -func GuessJSONStream(r io.Reader, size int) (io.Reader, []byte, bool) { - buffer := bufio.NewReaderSize(r, size) +func GuessJSONStream(r io.Reader, size int) (*StreamReader, []byte, bool) { + buffer := NewStreamReader(r, size) b, _ := buffer.Peek(size) - return buffer, b, hasJSONPrefix(b) + return buffer, b, IsJSONBuffer(b) } // IsJSONBuffer scans the provided buffer, looking // for an open brace indicating this is JSON. func IsJSONBuffer(buf []byte) bool { - return hasJSONPrefix(buf) + return hasPrefix(buf, jsonPrefix) } var jsonPrefix = []byte("{") -// hasJSONPrefix returns true if the provided buffer appears to start with -// a JSON open brace. -func hasJSONPrefix(buf []byte) bool { - return hasPrefix(buf, jsonPrefix) -} - // Return true if the first non-whitespace bytes in buf is // prefix. func hasPrefix(buf []byte, prefix []byte) bool { diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/stream_reader.go b/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/stream_reader.go new file mode 100644 index 000000000..d06991057 --- /dev/null +++ b/e2e/vendor/k8s.io/apimachinery/pkg/util/yaml/stream_reader.go @@ -0,0 +1,130 @@ +/* +Copyright 2025 The Kubernetes 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 yaml + +import "io" + +// StreamReader is a reader designed for consuming streams of variable-length +// messages. It buffers data until it is explicitly consumed, and can be +// rewound to re-read previous data. +type StreamReader struct { + r io.Reader + buf []byte + head int // current read offset into buf + ttlConsumed int // number of bytes which have been consumed +} + +// NewStreamReader creates a new StreamReader wrapping the provided +// io.Reader. +func NewStreamReader(r io.Reader, size int) *StreamReader { + if size == 0 { + size = 4096 + } + return &StreamReader{ + r: r, + buf: make([]byte, 0, size), // Start with a reasonable capacity + } +} + +// Read implements io.Reader. It first returns any buffered data after the +// current offset, and if that's exhausted, reads from the underlying reader +// and buffers the data. The returned data is not considered consumed until the +// Consume method is called. +func (r *StreamReader) Read(p []byte) (n int, err error) { + // If we have buffered data, return it + if r.head < len(r.buf) { + n = copy(p, r.buf[r.head:]) + r.head += n + return n, nil + } + + // If we've already hit EOF, return it + if r.r == nil { + return 0, io.EOF + } + + // Read from the underlying reader + n, err = r.r.Read(p) + if n > 0 { + r.buf = append(r.buf, p[:n]...) + r.head += n + } + if err == nil { + return n, nil + } + if err == io.EOF { + // Store that we've hit EOF by setting r to nil + r.r = nil + } + return n, err +} + +// ReadN reads exactly n bytes from the reader, blocking until all bytes are +// read or an error occurs. If an error occurs, the number of bytes read is +// returned along with the error. If EOF is hit before n bytes are read, this +// will return the bytes read so far, along with io.EOF. The returned data is +// not considered consumed until the Consume method is called. +func (r *StreamReader) ReadN(want int) ([]byte, error) { + ret := make([]byte, want) + off := 0 + for off < want { + n, err := r.Read(ret[off:]) + if err != nil { + return ret[:off+n], err + } + off += n + } + return ret, nil +} + +// Peek returns the next n bytes without advancing the reader. The returned +// bytes are valid until the next call to Consume. +func (r *StreamReader) Peek(n int) ([]byte, error) { + buf, err := r.ReadN(n) + r.RewindN(len(buf)) + if err != nil { + return buf, err + } + return buf, nil +} + +// Rewind resets the reader to the beginning of the buffered data. +func (r *StreamReader) Rewind() { + r.head = 0 +} + +// RewindN rewinds the reader by n bytes. If n is greater than the current +// buffer, the reader is rewound to the beginning of the buffer. +func (r *StreamReader) RewindN(n int) { + r.head -= min(n, r.head) +} + +// Consume discards up to n bytes of previously read data from the beginning of +// the buffer. Once consumed, that data is no longer available for rewinding. +// If n is greater than the current buffer, the buffer is cleared. Consume +// never consume data from the underlying reader. +func (r *StreamReader) Consume(n int) { + n = min(n, len(r.buf)) + r.buf = r.buf[n:] + r.head -= n + r.ttlConsumed += n +} + +// Consumed returns the number of bytes consumed from the input reader. +func (r *StreamReader) Consumed() int { + return r.ttlConsumed +} diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/version/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/version/doc.go index 29574fd6d..5f446a4f4 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/version/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/version/doc.go @@ -16,5 +16,5 @@ limitations under the License. // +k8s:openapi-gen=true -// Package version supplies the type for version information collected at build time. -package version // import "k8s.io/apimachinery/pkg/version" +// Package version supplies the type for version information. +package version diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/version/types.go b/e2e/vendor/k8s.io/apimachinery/pkg/version/types.go index 72727b503..6a18f9e91 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/version/types.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/version/types.go @@ -20,15 +20,25 @@ package version // TODO: Add []string of api versions supported? It's still unclear // how we'll want to distribute that information. type Info struct { - Major string `json:"major"` - Minor string `json:"minor"` - GitVersion string `json:"gitVersion"` - GitCommit string `json:"gitCommit"` - GitTreeState string `json:"gitTreeState"` - BuildDate string `json:"buildDate"` - GoVersion string `json:"goVersion"` - Compiler string `json:"compiler"` - Platform string `json:"platform"` + // Major is the major version of the binary version + Major string `json:"major"` + // Minor is the minor version of the binary version + Minor string `json:"minor"` + // EmulationMajor is the major version of the emulation version + EmulationMajor string `json:"emulationMajor,omitempty"` + // EmulationMinor is the minor version of the emulation version + EmulationMinor string `json:"emulationMinor,omitempty"` + // MinCompatibilityMajor is the major version of the minimum compatibility version + MinCompatibilityMajor string `json:"minCompatibilityMajor,omitempty"` + // MinCompatibilityMinor is the minor version of the minimum compatibility version + MinCompatibilityMinor string `json:"minCompatibilityMinor,omitempty"` + GitVersion string `json:"gitVersion"` + GitCommit string `json:"gitCommit"` + GitTreeState string `json:"gitTreeState"` + BuildDate string `json:"buildDate"` + GoVersion string `json:"goVersion"` + Compiler string `json:"compiler"` + Platform string `json:"platform"` } // String returns info as a human-friendly version string. diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/watch/doc.go b/e2e/vendor/k8s.io/apimachinery/pkg/watch/doc.go index 7e6bf3fb9..5fde5e742 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/watch/doc.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/watch/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package watch contains a generic watchable interface, and a fake for // testing code that uses the watch interface. -package watch // import "k8s.io/apimachinery/pkg/watch" +package watch diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher.go b/e2e/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher.go index 42dcac2b9..b422ca9f5 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher.go @@ -51,6 +51,7 @@ type Reporter interface { // StreamWatcher turns any stream for which you can write a Decoder interface // into a watch.Interface. type StreamWatcher struct { + logger klog.Logger sync.Mutex source Decoder reporter Reporter @@ -59,8 +60,16 @@ type StreamWatcher struct { } // NewStreamWatcher creates a StreamWatcher from the given decoder. +// +// Contextual logging: NewStreamWatcherWithLogger should be used instead of NewStreamWatcher in code which supports contextual logging. func NewStreamWatcher(d Decoder, r Reporter) *StreamWatcher { + return NewStreamWatcherWithLogger(klog.Background(), d, r) +} + +// NewStreamWatcherWithLogger creates a StreamWatcher from the given decoder and logger. +func NewStreamWatcherWithLogger(logger klog.Logger, d Decoder, r Reporter) *StreamWatcher { sw := &StreamWatcher{ + logger: logger, source: d, reporter: r, // It's easy for a consumer to add buffering via an extra @@ -98,7 +107,7 @@ func (sw *StreamWatcher) Stop() { // receive reads result from the decoder in a loop and sends down the result channel. func (sw *StreamWatcher) receive() { - defer utilruntime.HandleCrash() + defer utilruntime.HandleCrashWithLogger(sw.logger) defer close(sw.result) defer sw.Stop() for { @@ -108,10 +117,10 @@ func (sw *StreamWatcher) receive() { case io.EOF: // watch closed normally case io.ErrUnexpectedEOF: - klog.V(1).Infof("Unexpected EOF during watch stream event decoding: %v", err) + sw.logger.V(1).Info("Unexpected EOF during watch stream event decoding", "err", err) default: if net.IsProbableEOF(err) || net.IsTimeout(err) { - klog.V(5).Infof("Unable to decode an event from the watch stream: %v", err) + sw.logger.V(5).Info("Unable to decode an event from the watch stream", "err", err) } else { select { case <-sw.done: diff --git a/e2e/vendor/k8s.io/apimachinery/pkg/watch/watch.go b/e2e/vendor/k8s.io/apimachinery/pkg/watch/watch.go index ce37fd8c1..251459834 100644 --- a/e2e/vendor/k8s.io/apimachinery/pkg/watch/watch.go +++ b/e2e/vendor/k8s.io/apimachinery/pkg/watch/watch.go @@ -23,6 +23,7 @@ import ( "k8s.io/klog/v2" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) // Interface can be implemented by anything that knows how to watch and report changes. @@ -103,21 +104,34 @@ func (w emptyWatch) ResultChan() <-chan Event { // FakeWatcher lets you test anything that consumes a watch.Interface; threadsafe. type FakeWatcher struct { + logger klog.Logger result chan Event stopped bool sync.Mutex } +var _ Interface = &FakeWatcher{} + +// Contextual logging: NewFakeWithOptions and a logger in the FakeOptions should be used instead in code which supports contextual logging. func NewFake() *FakeWatcher { + return NewFakeWithOptions(FakeOptions{}) +} + +// Contextual logging: NewFakeWithOptions and a logger in the FakeOptions should be used instead in code which supports contextual logging. +func NewFakeWithChanSize(size int, blocking bool) *FakeWatcher { + return NewFakeWithOptions(FakeOptions{ChannelSize: size}) +} + +func NewFakeWithOptions(options FakeOptions) *FakeWatcher { return &FakeWatcher{ - result: make(chan Event), + logger: ptr.Deref(options.Logger, klog.Background()), + result: make(chan Event, options.ChannelSize), } } -func NewFakeWithChanSize(size int, blocking bool) *FakeWatcher { - return &FakeWatcher{ - result: make(chan Event, size), - } +type FakeOptions struct { + Logger *klog.Logger + ChannelSize int } // Stop implements Interface.Stop(). @@ -125,7 +139,7 @@ func (f *FakeWatcher) Stop() { f.Lock() defer f.Unlock() if !f.stopped { - klog.V(4).Infof("Stopping fake watcher.") + f.logger.V(4).Info("Stopping fake watcher") close(f.result) f.stopped = true } @@ -176,13 +190,22 @@ func (f *FakeWatcher) Action(action EventType, obj runtime.Object) { // RaceFreeFakeWatcher lets you test anything that consumes a watch.Interface; threadsafe. type RaceFreeFakeWatcher struct { + logger klog.Logger result chan Event Stopped bool sync.Mutex } +var _ Interface = &RaceFreeFakeWatcher{} + +// Contextual logging: RaceFreeFakeWatcherWithLogger should be used instead of NewRaceFreeFake in code which supports contextual logging. func NewRaceFreeFake() *RaceFreeFakeWatcher { + return NewRaceFreeFakeWithLogger(klog.Background()) +} + +func NewRaceFreeFakeWithLogger(logger klog.Logger) *RaceFreeFakeWatcher { return &RaceFreeFakeWatcher{ + logger: logger, result: make(chan Event, DefaultChanSize), } } @@ -192,7 +215,7 @@ func (f *RaceFreeFakeWatcher) Stop() { f.Lock() defer f.Unlock() if !f.Stopped { - klog.V(4).Infof("Stopping fake watcher.") + f.logger.V(4).Info("Stopping fake watcher") close(f.result) f.Stopped = true } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/doc.go index 087162e36..63ab31039 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +k8s:deepcopy-gen=package -package webhookadmission // import "k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission" +package webhookadmission diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/doc.go index 58875a59f..92cfed107 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +groupName=apiserver.config.k8s.io // Package v1 is the v1 version of the API. -package v1 // import "k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1" +package v1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/doc.go index c8ee58d5d..703f467f9 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +groupName=apiserver.config.k8s.io // Package v1alpha1 is the v1alpha1 version of the API. -package v1alpha1 // import "k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/doc.go index 6e86a1b5f..cac04f5b2 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package errors contains utilities for admission webhook specific errors -package errors // import "k8s.io/apiserver/pkg/admission/plugin/webhook/errors" +package errors diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/doc.go index d804aca1c..664a9a69a 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package mutating makes calls to mutating webhooks during the admission // process. -package mutating // import "k8s.io/apiserver/pkg/admission/plugin/webhook/mutating" +package mutating diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/doc.go index 660001dff..6899b55d8 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Package namespace defines the utilities that are used by the webhook // plugin to decide if a webhook should be applied to an object based on its // namespace. -package namespace // import "k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace" +package namespace diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/doc.go index 8964afa6c..8dc71abba 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Package object defines the utilities that are used by the webhook plugin to // decide if a webhook should run, as long as either the old object or the new // object has labels matching the webhook config's objectSelector. -package object // import "k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object" +package object diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/request/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/request/doc.go index fbacf3371..8e207e627 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/request/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/request/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package request creates admissionReview request based on admission attributes. -package request // import "k8s.io/apiserver/pkg/admission/plugin/webhook/request" +package request diff --git a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/doc.go index ede53c668..1dcc4b696 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package validating makes calls to validating (i.e., non-mutating) webhooks // during the admission process. -package validating // import "k8s.io/apiserver/pkg/admission/plugin/webhook/validating" +package validating diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apidiscovery/v2/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apidiscovery/v2/doc.go index 579dc0bb2..814fb2555 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apidiscovery/v2/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apidiscovery/v2/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +groupName=apidiscovery.k8s.io -package v2 // import "k8s.io/apiserver/pkg/apis/apidiscovery/v2" +package v2 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/doc.go index 88db1ffa6..1902ea645 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/doc.go @@ -18,4 +18,4 @@ limitations under the License. // +groupName=apiserver.k8s.io // Package apiserver is the internal version of the API. -package apiserver // import "k8s.io/apiserver/pkg/apis/apiserver" +package apiserver diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/doc.go index 91458aee4..6bd9e6bb1 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +groupName=apiserver.config.k8s.io // Package v1 is the v1 version of the API. -package v1 // import "k8s.io/apiserver/pkg/apis/apiserver/v1" +package v1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/doc.go index c9b658b22..d5277f182 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/doc.go @@ -21,4 +21,4 @@ limitations under the License. // +groupName=apiserver.config.k8s.io // Package v1alpha1 is the v1alpha1 version of the API. -package v1alpha1 // import "k8s.io/apiserver/pkg/apis/apiserver/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go index dee2c115a..0a50799c2 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/types.go @@ -352,7 +352,9 @@ type ClaimMappings struct { // If username.expression uses 'claims.email', then 'claims.email_verified' must be used in // username.expression or extra[*].valueExpression or claimValidationRules[*].expression. // An example claim validation rule expression that matches the validation automatically - // applied when username.claim is set to 'email' is 'claims.?email_verified.orValue(true)'. + // applied when username.claim is set to 'email' is 'claims.?email_verified.orValue(true) == true'. By explicitly comparing + // the value to true, we let type-checking see the result will be a boolean, and to make sure a non-boolean email_verified + // claim will be caught at runtime. // // In the flag based approach, the --oidc-username-claim and --oidc-username-prefix are optional. If --oidc-username-claim is not set, // the default value is "sub". For the authentication config, there is no defaulting for claim or prefix. The claim and prefix must be set explicitly. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/doc.go index 07321e775..39c0efc93 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +groupName=apiserver.k8s.io // Package v1beta1 is the v1beta1 version of the API. -package v1beta1 // import "k8s.io/apiserver/pkg/apis/apiserver/v1beta1" +package v1beta1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go index a0e13593b..72fe602b9 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/types.go @@ -323,7 +323,9 @@ type ClaimMappings struct { // If username.expression uses 'claims.email', then 'claims.email_verified' must be used in // username.expression or extra[*].valueExpression or claimValidationRules[*].expression. // An example claim validation rule expression that matches the validation automatically - // applied when username.claim is set to 'email' is 'claims.?email_verified.orValue(true)'. + // applied when username.claim is set to 'email' is 'claims.?email_verified.orValue(true) == true'. By explicitly comparing + // the value to true, we let type-checking see the result will be a boolean, and to make sure a non-boolean email_verified + // claim will be caught at runtime. // // In the flag based approach, the --oidc-username-claim and --oidc-username-prefix are optional. If --oidc-username-claim is not set, // the default value is "sub". For the authentication config, there is no defaulting for claim or prefix. The claim and prefix must be set explicitly. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/doc.go index deda9cbd6..90b516b34 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +groupName=audit.k8s.io -package audit // import "k8s.io/apiserver/pkg/apis/audit" +package audit diff --git a/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/v1/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/v1/doc.go index d1f180c94..6c719b847 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/v1/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/apis/audit/v1/doc.go @@ -22,4 +22,4 @@ limitations under the License. // +groupName=audit.k8s.io -package v1 // import "k8s.io/apiserver/pkg/apis/audit/v1" +package v1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/doc.go index 8f3d36b66..570c1ac59 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package x509 provides a request authenticator that validates and // extracts user information from client certificates -package x509 // import "k8s.io/apiserver/pkg/authentication/request/x509" +package x509 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509.go b/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509.go index bdc1b1790..fc827208b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/authentication/request/x509/x509.go @@ -21,15 +21,19 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/hex" + "errors" "fmt" "net/http" "strings" "time" + asn1util "k8s.io/apimachinery/pkg/apis/asn1" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/features" + utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/component-base/metrics" "k8s.io/component-base/metrics/legacyregistry" ) @@ -281,9 +285,14 @@ var CommonNameUserConversion = UserConversionFunc(func(chain []*x509.Certificate fp := sha256.Sum256(chain[0].Raw) id := "X509SHA256=" + hex.EncodeToString(fp[:]) + uid, err := parseUIDFromCert(chain[0]) + if err != nil { + return nil, false, err + } return &authenticator.Response{ User: &user.DefaultInfo{ Name: chain[0].Subject.CommonName, + UID: uid, Groups: chain[0].Subject.Organization, Extra: map[string][]string{ user.CredentialIDKey: {id}, @@ -291,3 +300,33 @@ var CommonNameUserConversion = UserConversionFunc(func(chain []*x509.Certificate }, }, true, nil }) + +var uidOID = asn1util.X509UID() + +func parseUIDFromCert(cert *x509.Certificate) (string, error) { + if !utilfeature.DefaultFeatureGate.Enabled(features.AllowParsingUserUIDFromCertAuth) { + return "", nil + } + + uids := []string{} + for _, name := range cert.Subject.Names { + if !name.Type.Equal(uidOID) { + continue + } + uid, ok := name.Value.(string) + if !ok { + return "", fmt.Errorf("unable to parse UID into a string") + } + uids = append(uids, uid) + } + if len(uids) == 0 { + return "", nil + } + if len(uids) != 1 { + return "", fmt.Errorf("expected 1 UID, but found multiple: %v", uids) + } + if uids[0] == "" { + return "", errors.New("UID cannot be an empty string") + } + return uids[0], nil +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/authentication/user/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/authentication/user/doc.go index 3d87fd72c..570c51ae9 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/authentication/user/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/authentication/user/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package user contains utilities for dealing with simple user exchange in the auth // packages. The user.Info interface defines an interface for exchanging that info. -package user // import "k8s.io/apiserver/pkg/authentication/user" +package user diff --git a/e2e/vendor/k8s.io/apiserver/pkg/authorization/path/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/authorization/path/doc.go index 654aaeb74..743d945b4 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/authorization/path/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/authorization/path/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package path contains an authorizer that allows certain paths and path prefixes. -package path // import "k8s.io/apiserver/pkg/authorization/path" +package path diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/environment/base.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/environment/base.go index b210377ae..a258fdec4 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/environment/base.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/environment/base.go @@ -32,9 +32,9 @@ import ( celconfig "k8s.io/apiserver/pkg/apis/cel" "k8s.io/apiserver/pkg/cel/library" genericfeatures "k8s.io/apiserver/pkg/features" + "k8s.io/apiserver/pkg/util/compatibility" utilfeature "k8s.io/apiserver/pkg/util/feature" - "k8s.io/component-base/featuregate" - utilversion "k8s.io/component-base/version" + basecompatibility "k8s.io/component-base/compatibility" ) // DefaultCompatibilityVersion returns a default compatibility version for use with EnvSet @@ -50,9 +50,9 @@ import ( // A default version number equal to the current Kubernetes major.minor version // indicates fast forward CEL features that can be used when rollback is no longer needed. func DefaultCompatibilityVersion() *version.Version { - effectiveVer := featuregate.DefaultComponentGlobalsRegistry.EffectiveVersionFor(featuregate.DefaultKubeComponent) + effectiveVer := compatibility.DefaultComponentGlobalsRegistry.EffectiveVersionFor(basecompatibility.DefaultKubeComponent) if effectiveVer == nil { - effectiveVer = utilversion.DefaultKubeEffectiveVersion() + effectiveVer = compatibility.DefaultBuildEffectiveVersion() } return effectiveVer.MinCompatibilityVersion() } @@ -173,7 +173,14 @@ var baseOptsWithoutStrictCost = []VersionedOptions{ { IntroducedVersion: version.MajorMinor(1, 32), EnvOptions: []cel.EnvOption{ - UnversionedLib(ext.TwoVarComprehensions), + ext.TwoVarComprehensions(), + }, + }, + // Semver + { + IntroducedVersion: version.MajorMinor(1, 33), + EnvOptions: []cel.EnvOption{ + library.SemverLib(library.SemverVersion(1)), }, }, } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cidr.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cidr.go index 2992e99e6..a638fd4ac 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cidr.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cidr.go @@ -160,9 +160,7 @@ var cidrLibraryDecls = map[string][]cel.FunctionOpt{ } func (*cidrs) CompileOptions() []cel.EnvOption { - options := []cel.EnvOption{cel.Types(apiservercel.CIDRType), - cel.Variable(apiservercel.CIDRType.TypeName(), types.NewTypeTypeWithParam(apiservercel.CIDRType)), - } + options := []cel.EnvOption{cel.Types(apiservercel.CIDRType)} for name, overloads := range cidrLibraryDecls { options = append(options, cel.Function(name, overloads...)) } @@ -231,8 +229,7 @@ func cidrContainsCIDR(arg ref.Val, other ref.Val) ref.Val { return types.MaybeNoSuchOverloadErr(other) } - equalMasked := cidr.Prefix.Masked() == netip.PrefixFrom(containsCIDR.Prefix.Addr(), cidr.Prefix.Bits()) - return types.Bool(equalMasked && cidr.Prefix.Bits() <= containsCIDR.Prefix.Bits()) + return types.Bool(cidr.Overlaps(containsCIDR.Prefix) && cidr.Prefix.Bits() <= containsCIDR.Prefix.Bits()) } func prefixLength(arg ref.Val) ref.Val { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cost.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cost.go index a9e5db811..47dbe7aa6 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cost.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/cost.go @@ -18,13 +18,14 @@ package library import ( "fmt" + "math" + "github.com/google/cel-go/checker" "github.com/google/cel-go/common" "github.com/google/cel-go/common/ast" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" "github.com/google/cel-go/common/types/traits" - "math" "k8s.io/apiserver/pkg/cel" ) @@ -202,7 +203,7 @@ func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, re return &cost } - case "quantity", "isQuantity": + case "quantity", "isQuantity", "semver", "isSemver": if len(args) >= 1 { cost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor)) return &cost @@ -236,7 +237,7 @@ func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, re // Simply dictionary lookup cost := uint64(1) return &cost - case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub": + case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub", "major", "minor", "patch": cost := uint64(1) return &cost case "getScheme", "getHostname", "getHost", "getPort", "getEscapedPath", "getQuery": @@ -486,7 +487,7 @@ func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *ch return &checker.CallEstimate{CostEstimate: ipCompCost} } - case "quantity", "isQuantity": + case "quantity", "isQuantity", "semver", "isSemver": if target != nil { sz := l.sizeEstimate(args[0]) return &checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor)} @@ -498,7 +499,7 @@ func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *ch } case "format.named": return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}} - case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub": + case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub", "major", "minor", "patch": return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}} case "getScheme", "getHostname", "getHost", "getPort", "getEscapedPath", "getQuery": // url accessors diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/format.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/format.go index 82ecffb41..2adc35c90 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/format.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/format.go @@ -20,7 +20,6 @@ import ( "fmt" "net/url" - "github.com/asaskevich/govalidator" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/decls" "github.com/google/cel-go/common/types" @@ -32,6 +31,13 @@ import ( "k8s.io/kube-openapi/pkg/validation/strfmt" ) +var ( + // base64_length estimate for base64 regex size from github.com/asaskevich/govalidator + base64Length = 84 + // url_length estimate for url regex size from github.com/asaskevich/govalidator + urlLength = 1103 +) + // Format provides a CEL library exposing common named Kubernetes string // validations. Can be used in CRD ValidationRules messageExpression. // @@ -193,7 +199,7 @@ var ConstantFormats = map[string]apiservercel.Format{ }, // Use govalidator url regex to estimate, since ParseRequestURI // doesnt use regex - MaxRegexSize: len(govalidator.URL), + MaxRegexSize: urlLength, }, "uuid": { Name: "uuid", @@ -213,7 +219,7 @@ var ConstantFormats = map[string]apiservercel.Format{ } return nil }, - MaxRegexSize: len(govalidator.Base64), + MaxRegexSize: base64Length, }, "date": { Name: "date", diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/ip.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/ip.go index 8edc4463a..5a089ae1c 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/ip.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/ip.go @@ -187,9 +187,7 @@ var ipLibraryDecls = map[string][]cel.FunctionOpt{ } func (*ip) CompileOptions() []cel.EnvOption { - options := []cel.EnvOption{cel.Types(apiservercel.IPType), - cel.Variable(apiservercel.IPType.TypeName(), types.NewTypeTypeWithParam(apiservercel.IPType)), - } + options := []cel.EnvOption{cel.Types(apiservercel.IPType)} for name, overloads := range ipLibraryDecls { options = append(options, cel.Function(name, overloads...)) } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/semverlib.go b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/semverlib.go index d8c79ae02..93614f849 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/cel/library/semverlib.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/cel/library/semverlib.go @@ -17,6 +17,10 @@ limitations under the License. package library import ( + "errors" + "math" + "strings" + "github.com/blang/semver/v4" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" @@ -31,8 +35,10 @@ import ( // // Converts a string to a semantic version or results in an error if the string is not a valid semantic version. Refer // to semver.org documentation for information on accepted patterns. -// +// An optional "normalize" argument can be passed to enable normalization. Normalization removes any "v" prefix, adds a +// 0 minor and patch numbers to versions with only major or major.minor components specified, and removes any leading 0s. // semver() +// semver(, ) // // Examples: // @@ -41,19 +47,28 @@ import ( // semver('200K') // error // semver('Three') // error // semver('Mi') // error +// semver('v1.0.0', true) // Applies normalization to remove the leading "v". Returns a Semver of "1.0.0". +// semver('1.0', true) // Applies normalization to add the missing patch version. Returns a Semver of "1.0.0" +// semver('01.01.01', true) // Applies normalization to remove leading zeros. Returns a Semver of "1.1.1" // // isSemver // // Returns true if a string is a valid Semver. isSemver returns true if and // only if semver does not result in error. +// An optional "normalize" argument can be passed to enable normalization. Normalization removes any "v" prefix, adds a +// 0 minor and patch numbers to versions with only major or major.minor components specified, and removes any leading 0s. // // isSemver( ) +// isSemver( , ) // // Examples: // // isSemver('1.0.0') // returns true -// isSemver('v1.0') // returns true (tolerant parsing) // isSemver('hello') // returns false +// isSemver('v1.0') // returns false (leading "v" is not allowed unless normalization is enabled) +// isSemver('v1.0', true) // Applies normalization to remove leading "v". returns true +// semver('1.0', true) // Applies normalization to add the missing patch version. Returns true +// semver('01.01.01', true) // Applies normalization to remove leading zeros. Returns true // // Conversion to Scalars: // @@ -84,13 +99,29 @@ import ( // semver("1.2.3").compareTo(semver("2.0.0")) // returns -1 // semver("1.2.3").compareTo(semver("0.1.2")) // returns 1 -func SemverLib() cel.EnvOption { +func SemverLib(options ...SemverOption) cel.EnvOption { + semverLib := &semverLibType{} + for _, o := range options { + semverLib = o(semverLib) + } return cel.Lib(semverLib) } -var semverLib = &semverLibType{} +var semverLib = &semverLibType{version: math.MaxUint32} // include all versions -type semverLibType struct{} +type semverLibType struct { + version uint32 +} + +// StringsOption is a functional interface for configuring the strings library. +type SemverOption func(*semverLibType) *semverLibType + +func SemverVersion(version uint32) SemverOption { + return func(lib *semverLibType) *semverLibType { + lib.version = version + return lib + } +} func (*semverLibType) LibraryName() string { return "kubernetes.Semver" @@ -100,8 +131,8 @@ func (*semverLibType) Types() []*cel.Type { return []*cel.Type{apiservercel.SemverType} } -func (*semverLibType) declarations() map[string][]cel.FunctionOpt { - return map[string][]cel.FunctionOpt{ +func (lib *semverLibType) declarations() map[string][]cel.FunctionOpt { + fnOpts := map[string][]cel.FunctionOpt{ "semver": { cel.Overload("string_to_semver", []*cel.Type{cel.StringType}, apiservercel.SemverType, cel.UnaryBinding((stringToSemver))), }, @@ -127,6 +158,11 @@ func (*semverLibType) declarations() map[string][]cel.FunctionOpt { cel.MemberOverload("semver_patch", []*cel.Type{apiservercel.SemverType}, cel.IntType, cel.UnaryBinding(semverPatch)), }, } + if lib.version >= 1 { + fnOpts["semver"] = append(fnOpts["semver"], cel.Overload("string_bool_to_semver", []*cel.Type{cel.StringType, cel.BoolType}, apiservercel.SemverType, cel.BinaryBinding((stringToSemverNormalize)))) + fnOpts["isSemver"] = append(fnOpts["isSemver"], cel.Overload("is_semver_string_bool", []*cel.Type{cel.StringType, cel.BoolType}, cel.BoolType, cel.BinaryBinding(isSemverNormalize))) + } + return fnOpts } func (s *semverLibType) CompileOptions() []cel.EnvOption { @@ -144,16 +180,29 @@ func (*semverLibType) ProgramOptions() []cel.ProgramOption { } func isSemver(arg ref.Val) ref.Val { + return isSemverNormalize(arg, types.Bool(false)) +} +func isSemverNormalize(arg ref.Val, normalizeArg ref.Val) ref.Val { str, ok := arg.Value().(string) if !ok { return types.MaybeNoSuchOverloadErr(arg) } + normalize, ok := normalizeArg.Value().(bool) + if !ok { + return types.MaybeNoSuchOverloadErr(arg) + } + // Using semver/v4 here is okay because this function isn't // used to validate the Kubernetes API. In the CEL base library // we would have to use the regular expression from // pkg/apis/resource/structured/namedresources/validation/validation.go. - _, err := semver.Parse(str) + var err error + if normalize { + _, err = normalizeAndParse(str) + } else { + _, err = semver.Parse(str) + } if err != nil { return types.Bool(false) } @@ -162,17 +211,31 @@ func isSemver(arg ref.Val) ref.Val { } func stringToSemver(arg ref.Val) ref.Val { + return stringToSemverNormalize(arg, types.Bool(false)) +} +func stringToSemverNormalize(arg ref.Val, normalizeArg ref.Val) ref.Val { str, ok := arg.Value().(string) if !ok { return types.MaybeNoSuchOverloadErr(arg) } + normalize, ok := normalizeArg.Value().(bool) + if !ok { + return types.MaybeNoSuchOverloadErr(arg) + } + // Using semver/v4 here is okay because this function isn't // used to validate the Kubernetes API. In the CEL base library // we would have to use the regular expression from // pkg/apis/resource/structured/namedresources/validation/validation.go // first before parsing. - v, err := semver.Parse(str) + var err error + var v semver.Version + if normalize { + v, err = normalizeAndParse(str) + } else { + v, err = semver.Parse(str) + } if err != nil { return types.WrapErr(err) } @@ -245,3 +308,37 @@ func semverCompareTo(arg ref.Val, other ref.Val) ref.Val { return types.Int(v.Compare(v2)) } + +// normalizeAndParse removes any "v" prefix, adds a 0 minor and patch numbers to versions with +// only major or major.minor components specified, and removes any leading 0s. +// normalizeAndParse is based on semver.ParseTolerant but does not trim extra whitespace and is +// guaranteed to not change behavior in the future. +func normalizeAndParse(s string) (semver.Version, error) { + s = strings.TrimPrefix(s, "v") + + // Split into major.minor.(patch+pr+meta) + parts := strings.SplitN(s, ".", 3) + // Remove leading zeros. + for i, p := range parts { + if len(p) > 1 { + p = strings.TrimLeft(p, "0") + if len(p) == 0 || !strings.ContainsAny(p[0:1], "0123456789") { + p = "0" + p + } + parts[i] = p + } + } + + // Fill up shortened versions. + if len(parts) < 3 { + if strings.ContainsAny(parts[len(parts)-1], "+-") { + return semver.Version{}, errors.New("short version cannot contain PreRelease/Build meta data") + } + for len(parts) < 3 { + parts = append(parts, "0") + } + } + s = strings.Join(parts, ".") + + return semver.Parse(s) +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/fake.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/fake.go index e3c7fcfa7..4146dc011 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/fake.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/fake.go @@ -25,7 +25,7 @@ import ( "time" "github.com/emicklei/go-restful/v3" - "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp" //nolint:depguard apidiscoveryv2 "k8s.io/api/apidiscovery/v2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go index 338be85a2..3ea59e873 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go @@ -29,6 +29,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/version" apidiscoveryv2conversion "k8s.io/apiserver/pkg/apis/apidiscovery/v2" + genericfeatures "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" @@ -40,6 +41,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" + utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/klog/v2" ) @@ -538,6 +540,14 @@ func (rdm *resourceDiscoveryManager) serveHTTP(resp http.ResponseWriter, req *ht resp.WriteHeader(http.StatusInternalServerError) return } + + if mediaType.Convert.GroupVersion() == apidiscoveryv2beta1.SchemeGroupVersion && + utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryRemoveBetaType) { + klog.Errorf("aggregated discovery version v2beta1 is removed. Please update to use v2") + resp.WriteHeader(http.StatusNotFound) + return + } + targetGV = mediaType.Convert.GroupVersion() if len(etag) > 0 { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go index 9900021a4..57d1d6103 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go @@ -18,6 +18,9 @@ package aggregated import ( "k8s.io/apimachinery/pkg/runtime/schema" + + genericfeatures "k8s.io/apiserver/pkg/features" + utilfeature "k8s.io/apiserver/pkg/util/feature" ) // Interface is from "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" @@ -37,6 +40,9 @@ func (discoveryEndpointRestrictions) AllowsStreamSchema(s string) bool { return // IsAggregatedDiscoveryGVK checks if a provided GVK is the GVK for serving aggregated discovery. func IsAggregatedDiscoveryGVK(gvk *schema.GroupVersionKind) bool { if gvk != nil { + if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryRemoveBetaType) { + return gvk.Group == "apidiscovery.k8s.io" && gvk.Version == "v2" && gvk.Kind == "APIGroupDiscoveryList" + } return gvk.Group == "apidiscovery.k8s.io" && (gvk.Version == "v2beta1" || gvk.Version == "v2") && gvk.Kind == "APIGroupDiscoveryList" } return false diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go index 25fe90fa4..c9f0907e7 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go @@ -28,8 +28,6 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" - genericfeatures "k8s.io/apiserver/pkg/features" - utilfeature "k8s.io/apiserver/pkg/util/feature" ) type WrappedHandler struct { @@ -39,13 +37,11 @@ type WrappedHandler struct { } func (wrapped *WrappedHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { - if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) { - mediaType, _ := negotiation.NegotiateMediaTypeOptions(req.Header.Get("Accept"), wrapped.s.SupportedMediaTypes(), DiscoveryEndpointRestrictions) - // mediaType.Convert looks at the request accept headers and is used to control whether the discovery document will be aggregated. - if IsAggregatedDiscoveryGVK(mediaType.Convert) { - wrapped.aggHandler.ServeHTTP(resp, req) - return - } + mediaType, _ := negotiation.NegotiateMediaTypeOptions(req.Header.Get("Accept"), wrapped.s.SupportedMediaTypes(), DiscoveryEndpointRestrictions) + // mediaType.Convert looks at the request accept headers and is used to control whether the discovery document will be aggregated. + if IsAggregatedDiscoveryGVK(mediaType.Convert) { + wrapped.aggHandler.ServeHTTP(resp, req) + return } wrapped.handler.ServeHTTP(resp, req) } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/doc.go index ef99114b6..f92c0e95f 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package endpoints contains the generic code that provides a RESTful Kubernetes-style API service. -package endpoints // import "k8s.io/apiserver/pkg/endpoints" +package endpoints diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authentication.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authentication.go index 980e11f6e..26dd208ac 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authentication.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authentication.go @@ -68,6 +68,7 @@ func withAuthentication(handler http.Handler, auth authenticator.Request, failed authenticationFinish := time.Now() defer func() { metrics(req.Context(), resp, ok, err, apiAuds, authenticationStart, authenticationFinish) + genericapirequest.TrackAuthenticationLatency(req.Context(), authenticationFinish.Sub(authenticationStart)) }() if err != nil || !ok { if err != nil { @@ -118,7 +119,6 @@ func withAuthentication(handler http.Handler, auth authenticator.Request, failed // https://github.com/golang/net/commit/97aa3a539ec716117a9d15a4659a911f50d13c3c w.Header().Set("Connection", "close") } - req = req.WithContext(genericapirequest.WithUser(req.Context(), resp.User)) handler.ServeHTTP(w, req) }) diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authorization.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authorization.go index eec02e572..29acc4286 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authorization.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/authorization.go @@ -73,6 +73,7 @@ func withAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime. authorizationFinish := time.Now() defer func() { metrics(ctx, authorized, err, authorizationStart, authorizationFinish) + request.TrackAuthorizationLatency(ctx, authorizationFinish.Sub(authorizationStart)) }() // an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/doc.go index a13125a25..5fb108039 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/doc.go @@ -18,4 +18,4 @@ limitations under the License. // _are_ api related, i.e. which are prerequisite for the API services // to work (in contrast to the filters in the server package which are // not part of the API contract). -package filters // import "k8s.io/apiserver/pkg/endpoints/filters" +package filters diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/traces.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/traces.go index 6e36ffec8..a82edd456 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/traces.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/filters/traces.go @@ -24,6 +24,7 @@ import ( "go.opentelemetry.io/otel/trace" "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/authentication/user" tracing "k8s.io/component-base/tracing" ) @@ -31,7 +32,7 @@ import ( func WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler { opts := []otelhttp.Option{ otelhttp.WithPropagators(tracing.Propagators()), - otelhttp.WithPublicEndpoint(), + otelhttp.WithPublicEndpointFn(notSystemPrivilegedGroup), otelhttp.WithTracerProvider(tp), otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string { ctx := r.Context() @@ -43,6 +44,11 @@ func WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler { }), } wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Adjust otelhttp tracing start time to match the start time used + // for Prometheus metrics. + if startTime, ok := request.ReceivedTimestampFrom(r.Context()); ok { + r = r.WithContext(otelhttp.ContextWithStartTime(r.Context(), startTime)) + } // Add the http.target attribute to the otelhttp span // Workaround for https://github.com/open-telemetry/opentelemetry-go-contrib/issues/3743 if r.URL != nil { @@ -73,3 +79,14 @@ func getSpanNameFromRequestInfo(info *request.RequestInfo, r *http.Request) stri } return r.Method + " " + spanName } + +func notSystemPrivilegedGroup(req *http.Request) bool { + if u, ok := request.UserFrom(req.Context()); ok { + for _, group := range u.GetGroups() { + if group == user.SystemPrivilegedGroup || group == user.MonitoringGroup { + return false + } + } + } + return true +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/doc.go index d39833814..2dc42ffab 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package handlers contains HTTP handlers to implement the apiserver APIs. -package handlers // import "k8s.io/apiserver/pkg/endpoints/handlers" +package handlers diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/doc.go index 80f4feb72..1490b28fe 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package negotiation contains media type negotiation logic. -package negotiation // import "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" +package negotiation diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/doc.go index b76758b79..96ec55074 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package responsewriters containers helpers to write responses in HTTP handlers. -package responsewriters // import "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" +package responsewriters diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go index 3ca5cba8c..55f8b657a 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go @@ -157,6 +157,9 @@ const ( // (usually the entire object), and if the size is smaller no gzipping will be performed // if the client requests it. defaultGzipThresholdBytes = 128 * 1024 + // Use the length of the first write to recognize streaming implementations. + // When streaming JSON first write is "{", while Kubernetes protobuf starts unique 4 byte header. + firstWriteStreamingThresholdBytes = 4 ) // negotiateContentEncoding returns a supported client-requested content encoding for the @@ -192,34 +195,62 @@ type deferredResponseWriter struct { statusCode int contentEncoding string - hasWritten bool - hw http.ResponseWriter - w io.Writer + hasBuffered bool + buffer []byte + hasWritten bool + hw http.ResponseWriter + w io.Writer + // totalBytes is the number of bytes written to `w` and does not include buffered bytes + totalBytes int + // lastWriteErr holds the error result (if any) of the last write attempt to `w` + lastWriteErr error ctx context.Context } func (w *deferredResponseWriter) Write(p []byte) (n int, err error) { - ctx := w.ctx - span := tracing.SpanFromContext(ctx) - // This Step usually wraps in-memory object serialization. - span.AddEvent("About to start writing response", attribute.Int("size", len(p))) + switch { + case w.hasWritten: + // already written, cannot buffer + return w.unbufferedWrite(p) - firstWrite := !w.hasWritten - defer func() { - if err != nil { - span.AddEvent("Write call failed", - attribute.String("writer", fmt.Sprintf("%T", w.w)), - attribute.Int("size", len(p)), - attribute.Bool("firstWrite", firstWrite), - attribute.String("err", err.Error())) - } else { - span.AddEvent("Write call succeeded", - attribute.String("writer", fmt.Sprintf("%T", w.w)), - attribute.Int("size", len(p)), - attribute.Bool("firstWrite", firstWrite)) + case w.contentEncoding != "gzip": + // non-gzip, no need to buffer + return w.unbufferedWrite(p) + + case !w.hasBuffered && len(p) > defaultGzipThresholdBytes: + // not yet buffered, first write is long enough to trigger gzip, no need to buffer + return w.unbufferedWrite(p) + + case !w.hasBuffered && len(p) > firstWriteStreamingThresholdBytes: + // not yet buffered, first write is longer than expected for streaming scenarios that would require buffering, no need to buffer + return w.unbufferedWrite(p) + + default: + if !w.hasBuffered { + w.hasBuffered = true + // Start at 80 bytes to avoid rapid reallocation of the buffer. + // The minimum size of a 0-item serialized list object is 80 bytes: + // {"kind":"List","apiVersion":"v1","metadata":{"resourceVersion":"1"},"items":[]}\n + w.buffer = make([]byte, 0, max(80, len(p))) } + w.buffer = append(w.buffer, p...) + var err error + if len(w.buffer) > defaultGzipThresholdBytes { + // we've accumulated enough to trigger gzip, write and clear buffer + _, err = w.unbufferedWrite(w.buffer) + w.buffer = nil + } + return len(p), err + } +} + +func (w *deferredResponseWriter) unbufferedWrite(p []byte) (n int, err error) { + defer func() { + w.totalBytes += n + w.lastWriteErr = err }() + if w.hasWritten { return w.w.Write(p) } @@ -240,16 +271,45 @@ func (w *deferredResponseWriter) Write(p []byte) (n int, err error) { w.w = hw } + span := tracing.SpanFromContext(w.ctx) + span.AddEvent("About to start writing response", + attribute.String("writer", fmt.Sprintf("%T", w.w)), + attribute.Int("size", len(p)), + ) + header.Set("Content-Type", w.mediaType) hw.WriteHeader(w.statusCode) return w.w.Write(p) } -func (w *deferredResponseWriter) Close() error { +func (w *deferredResponseWriter) Close() (err error) { + defer func() { + if !w.hasWritten { + return + } + + span := tracing.SpanFromContext(w.ctx) + + if w.lastWriteErr != nil { + span.AddEvent("Write call failed", + attribute.Int("size", w.totalBytes), + attribute.String("err", w.lastWriteErr.Error())) + } else { + span.AddEvent("Write call succeeded", + attribute.Int("size", w.totalBytes)) + } + }() + if !w.hasWritten { - return nil + if !w.hasBuffered { + return nil + } + // never reached defaultGzipThresholdBytes, no need to do the gzip writer cleanup + _, err := w.unbufferedWrite(w.buffer) + w.buffer = nil + return err } - var err error + switch t := w.w.(type) { case *gzip.Writer: err = t.Close() diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/doc.go index 96da6f2b9..bf0ce9581 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/doc.go @@ -17,4 +17,4 @@ limitations under the License. // Package request contains everything around extracting info from // a http request object. // TODO: this package is temporary. Handlers must move into pkg/apiserver/handlers to avoid dependency cycle -package request // import "k8s.io/apiserver/pkg/endpoints/request" +package request diff --git a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go index 435af8e7c..bda43b617 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go @@ -116,6 +116,12 @@ type LatencyTrackers struct { // Validate webhooks are done in parallel, so max function is used. ValidatingWebhookTracker DurationTracker + // AuthenticationTracker tracks the latency incurred by Authentication of request + AuthenticationTracker DurationTracker + + // AuthorizationTracker tracks the latency incurred by Authorization of request + AuthorizationTracker DurationTracker + // APFQueueWaitTracker tracks the latency incurred by queue wait times // from priority & fairness. APFQueueWaitTracker DurationTracker @@ -179,6 +185,8 @@ func WithLatencyTrackersAndCustomClock(parent context.Context, c clock.Clock) co return WithValue(parent, latencyTrackersKey, &LatencyTrackers{ MutatingWebhookTracker: newSumLatencyTracker(c), ValidatingWebhookTracker: newMaxLatencyTracker(c), + AuthenticationTracker: newSumLatencyTracker(c), + AuthorizationTracker: newMaxLatencyTracker(c), APFQueueWaitTracker: newMaxLatencyTracker(c), StorageTracker: newSumLatencyTracker(c), TransformTracker: newSumLatencyTracker(c), @@ -243,6 +251,22 @@ func TrackResponseWriteLatency(ctx context.Context, d time.Duration) { } } +// TrackAuthenticationLatency is used to track latency incurred +// by Authentication phase of request. +func TrackAuthenticationLatency(ctx context.Context, d time.Duration) { + if tracker, ok := LatencyTrackersFrom(ctx); ok { + tracker.AuthenticationTracker.TrackDuration(d) + } +} + +// TrackAuthorizationLatency is used to track latency incurred +// by Authorization phase of request. +func TrackAuthorizationLatency(ctx context.Context, d time.Duration) { + if tracker, ok := LatencyTrackersFrom(ctx); ok { + tracker.AuthorizationTracker.TrackDuration(d) + } +} + // TrackAPFQueueWaitLatency is used to track latency incurred // by priority and fairness queues. func TrackAPFQueueWaitLatency(ctx context.Context, d time.Duration) { @@ -275,6 +299,8 @@ func AuditAnnotationsFromLatencyTrackers(ctx context.Context) map[string]string validatingWebhookLatencyKey = "apiserver.latency.k8s.io/validating-webhook" decodeLatencyKey = "apiserver.latency.k8s.io/decode-response-object" apfQueueWaitLatencyKey = "apiserver.latency.k8s.io/apf-queue-wait" + authenticationLatencyKey = "apiserver.latency.k8s.io/authentication" + authorizationLatencyKey = "apiserver.latency.k8s.io/authorization" ) tracker, ok := LatencyTrackersFrom(ctx) @@ -307,5 +333,11 @@ func AuditAnnotationsFromLatencyTrackers(ctx context.Context) map[string]string if latency := tracker.APFQueueWaitTracker.GetLatency(); latency != 0 { annotations[apfQueueWaitLatencyKey] = latency.String() } + if latency := tracker.AuthenticationTracker.GetLatency(); latency != 0 { + annotations[authenticationLatencyKey] = latency.String() + } + if latency := tracker.AuthorizationTracker.GetLatency(); latency != 0 { + annotations[authorizationLatencyKey] = latency.String() + } return annotations } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/features/kube_features.go b/e2e/vendor/k8s.io/apiserver/pkg/features/kube_features.go index c23343346..0ede8f9cb 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/features/kube_features.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/features/kube_features.go @@ -34,19 +34,17 @@ const ( // of code conflicts because changes are more likely to be scattered // across the file. - // owner: @ivelichkovich, @tallclair - // stable: v1.30 - // kep: https://kep.k8s.io/3716 + // owner: @jefftree // - // Enables usage of MatchConditions fields to use CEL expressions for matching on admission webhooks - AdmissionWebhookMatchConditions featuregate.Feature = "AdmissionWebhookMatchConditions" + // Remove the v2beta1 apidiscovery.k8s.io/v2beta1 group version. Aggregated + // discovery implements its own handlers and follows a different lifecycle than + // traditional k8s resources. + AggregatedDiscoveryRemoveBetaType featuregate.Feature = "AggregatedDiscoveryRemoveBetaType" - // owner: @jefftree @alexzielenski - // stable: v1.30 + // owner: @modulitos // - // Enables an single HTTP endpoint /discovery/ which supports native HTTP - // caching with ETags containing all APIResources known to the apiserver. - AggregatedDiscoveryEndpoint featuregate.Feature = "AggregatedDiscoveryEndpoint" + // Allow user.DefaultInfo.UID to be set from x509 cert during cert auth. + AllowParsingUserUIDFromCertAuth featuregate.Feature = "AllowParsingUserUIDFromCertAuth" // owner: @vinayakankugoyal // kep: https://kep.k8s.io/4633 @@ -63,13 +61,6 @@ const ( // resources using the Kubernetes API only. AllowUnsafeMalformedObjectDeletion featuregate.Feature = "AllowUnsafeMalformedObjectDeletion" - // owner: @smarterclayton - // stable: 1.29 - // - // Allow API clients to retrieve resource lists in chunks rather than - // all at once. - APIListChunking featuregate.Feature = "APIListChunking" - // owner: @ilackams // // Enables compression of REST responses (GET and LIST only) @@ -118,10 +109,6 @@ const ( // Enables coordinated leader election in the API server CoordinatedLeaderElection featuregate.Feature = "CoordinatedLeaderElection" - // - // Allows for updating watchcache resource version with progress notify events. - EfficientWatchResumption featuregate.Feature = "EfficientWatchResumption" - // owner: @aramase // kep: https://kep.k8s.io/3299 // deprecated: v1.28 @@ -129,6 +116,12 @@ const ( // Enables KMS v1 API for encryption at rest. KMSv1 featuregate.Feature = "KMSv1" + // owner: @serathius + // kep: https://kep.k8s.io/4988 + // + // Enables generating snapshots of watch cache store and using them to serve LIST requests. + ListFromCacheSnapshot featuregate.Feature = "ListFromCacheSnapshot" + // owner: @alexzielenski, @cici37, @jiahuif, @jpbetz // kep: https://kep.k8s.io/3962 // @@ -142,13 +135,6 @@ const ( // in the spec returned from kube-apiserver. OpenAPIEnums featuregate.Feature = "OpenAPIEnums" - // owner: @caesarxuchao - // stable: 1.29 - // - // Allow apiservers to show a count of remaining items in the response - // to a chunking list request. - RemainingItemCount featuregate.Feature = "RemainingItemCount" - // owner: @stlaz // // Enable kube-apiserver to accept UIDs via request header authentication. @@ -217,6 +203,14 @@ const ( // document. StorageVersionHash featuregate.Feature = "StorageVersionHash" + // owner: @serathius + // Allow API server JSON encoder to encode collections item by item, instead of all at once. + StreamingCollectionEncodingToJSON featuregate.Feature = "StreamingCollectionEncodingToJSON" + + // owner: @serathius + // Allow API server Protobuf encoder to encode collections item by item, instead of all at once. + StreamingCollectionEncodingToProtobuf featuregate.Feature = "StreamingCollectionEncodingToProtobuf" + // owner: @aramase, @enj, @nabokihms // kep: https://kep.k8s.io/3331 // @@ -229,11 +223,6 @@ const ( // Enables Structured Authorization Configuration StructuredAuthorizationConfiguration featuregate.Feature = "StructuredAuthorizationConfiguration" - // owner: @wojtek-t - // - // Enables support for watch bookmark events. - WatchBookmark featuregate.Feature = "WatchBookmark" - // owner: @wojtek-t // // Enables post-start-hook for storage readiness @@ -257,7 +246,6 @@ const ( ) func init() { - runtime.Must(utilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates)) runtime.Must(utilfeature.DefaultMutableFeatureGate.AddVersioned(defaultVersionedKubernetesFeatureGates)) } @@ -268,16 +256,13 @@ func init() { // Entries are alphabetized and separated from each other with blank lines to avoid sweeping gofmt changes // when adding or removing one entry. var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate.VersionedSpecs{ - AdmissionWebhookMatchConditions: { - {Version: version.MustParse("1.27"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.28"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.30"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, + AggregatedDiscoveryRemoveBetaType: { + {Version: version.MustParse("1.0"), Default: false, PreRelease: featuregate.GA}, + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Deprecated}, }, - AggregatedDiscoveryEndpoint: { - {Version: version.MustParse("1.26"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.27"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.30"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, + AllowParsingUserUIDFromCertAuth: { + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, }, AllowUnsafeMalformedObjectDeletion: { @@ -289,12 +274,6 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, }, - APIListChunking: { - {Version: version.MustParse("1.8"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.9"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.29"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - APIResponseCompression: { {Version: version.MustParse("1.8"), Default: false, PreRelease: featuregate.Alpha}, {Version: version.MustParse("1.16"), Default: true, PreRelease: featuregate.Beta}, @@ -316,6 +295,7 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate BtreeWatchCache: { {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, }, AuthorizeWithSelectors: { @@ -338,19 +318,19 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate CoordinatedLeaderElection: { {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Alpha}, - }, - - EfficientWatchResumption: { - {Version: version.MustParse("1.20"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.21"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.24"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, + {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Beta}, }, KMSv1: { + {Version: version.MustParse("1.0"), Default: true, PreRelease: featuregate.GA}, {Version: version.MustParse("1.28"), Default: true, PreRelease: featuregate.Deprecated}, {Version: version.MustParse("1.29"), Default: false, PreRelease: featuregate.Deprecated}, }, + ListFromCacheSnapshot: { + {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Alpha}, + }, + MutatingAdmissionPolicy: { {Version: version.MustParse("1.32"), Default: false, PreRelease: featuregate.Alpha}, }, @@ -360,14 +340,9 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.24"), Default: true, PreRelease: featuregate.Beta}, }, - RemainingItemCount: { - {Version: version.MustParse("1.15"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.16"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.29"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - RemoteRequestHeaderUID: { {Version: version.MustParse("1.32"), Default: false, PreRelease: featuregate.Alpha}, + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, }, ResilientWatchCacheInitialization: { @@ -382,6 +357,7 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate SeparateCacheWatchRPC: { {Version: version.MustParse("1.28"), Default: true, PreRelease: featuregate.Beta}, + {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Deprecated}, }, StorageVersionAPI: { @@ -393,6 +369,14 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.15"), Default: true, PreRelease: featuregate.Beta}, }, + StreamingCollectionEncodingToJSON: { + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, + }, + + StreamingCollectionEncodingToProtobuf: { + {Version: version.MustParse("1.33"), Default: true, PreRelease: featuregate.Beta}, + }, + StrictCostEnforcementForVAP: { {Version: version.MustParse("1.30"), Default: false, PreRelease: featuregate.Beta}, {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, @@ -419,26 +403,19 @@ var defaultVersionedKubernetesFeatureGates = map[featuregate.Feature]featuregate {Version: version.MustParse("1.29"), Default: true, PreRelease: featuregate.Beta}, }, - WatchBookmark: { - {Version: version.MustParse("1.15"), Default: false, PreRelease: featuregate.Alpha}, - {Version: version.MustParse("1.16"), Default: true, PreRelease: featuregate.Beta}, - {Version: version.MustParse("1.17"), Default: true, PreRelease: featuregate.GA, LockToDefault: true}, - }, - WatchCacheInitializationPostStartHook: { {Version: version.MustParse("1.31"), Default: false, PreRelease: featuregate.Beta}, }, WatchFromStorageWithoutResourceVersion: { {Version: version.MustParse("1.27"), Default: false, PreRelease: featuregate.Beta}, + {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Deprecated, LockToDefault: true}, }, WatchList: { {Version: version.MustParse("1.27"), Default: false, PreRelease: featuregate.Alpha}, {Version: version.MustParse("1.32"), Default: true, PreRelease: featuregate.Beta}, + // switch this back to false because the json and proto streaming encoders appear to work better. + {Version: version.MustParse("1.33"), Default: false, PreRelease: featuregate.Beta}, }, } - -// defaultKubernetesFeatureGates consists of legacy unversioned Kubernetes-specific feature keys. -// Please do not add to this struct and use defaultVersionedKubernetesFeatureGates instead. -var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/doc.go index ea79d130a..47bb95304 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package generic provides a generic object store interface and a // generic label/field matching type. -package generic // import "k8s.io/apiserver/pkg/registry/generic" +package generic diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/corrupt_obj_deleter.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/corrupt_obj_deleter.go index 4907da47f..2c37b0b5d 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/corrupt_obj_deleter.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/corrupt_obj_deleter.go @@ -107,8 +107,14 @@ func (d *corruptObjectDeleter) Delete(ctx context.Context, name string, deleteVa klog.FromContext(ctx).V(1).Info("Going to perform unsafe object deletion", "object", klog.KRef(genericapirequest.NamespaceValue(ctx), name)) out := d.store.NewFunc() storageOpts := storage.DeleteOptions{IgnoreStoreReadError: true} - // dropping preconditions, and keeping the admission - if err := storageBackend.Delete(ctx, key, out, nil, storage.ValidateObjectFunc(deleteValidation), nil, storageOpts); err != nil { + // we don't have the old object in the cache, neither can it be + // retrieved from the storage and decoded into an object + // successfully, so we do the following: + // a) skip preconditions check + // b) skip admission validation, rest.ValidateAllObjectFunc will "admit everything" + var nilPreconditions *storage.Preconditions = nil + var nilCachedExistingObject runtime.Object = nil + if err := storageBackend.Delete(ctx, key, out, nilPreconditions, rest.ValidateAllObjectFunc, nilCachedExistingObject, storageOpts); err != nil { if storage.IsNotFound(err) { // the DELETE succeeded, but we don't have the object since it's // not retrievable from the storage, so we send a nil object diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/doc.go index bd315ae47..643a6fb7b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package etcd has a generic implementation of a registry that // stores things in etcd. -package registry // import "k8s.io/apiserver/pkg/registry/generic/registry" +package registry diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go index 3c974f398..d36dd263f 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go @@ -54,31 +54,34 @@ func StorageWithCacher() generic.StorageDecorator { } cacherConfig := cacherstorage.Config{ - Storage: s, - Versioner: storage.APIObjectVersioner{}, - GroupResource: storageConfig.GroupResource, - ResourcePrefix: resourcePrefix, - KeyFunc: keyFunc, - NewFunc: newFunc, - NewListFunc: newListFunc, - GetAttrsFunc: getAttrsFunc, - IndexerFuncs: triggerFuncs, - Indexers: indexers, - Codec: storageConfig.Codec, + Storage: s, + Versioner: storage.APIObjectVersioner{}, + GroupResource: storageConfig.GroupResource, + EventsHistoryWindow: storageConfig.EventsHistoryWindow, + ResourcePrefix: resourcePrefix, + KeyFunc: keyFunc, + NewFunc: newFunc, + NewListFunc: newListFunc, + GetAttrsFunc: getAttrsFunc, + IndexerFuncs: triggerFuncs, + Indexers: indexers, + Codec: storageConfig.Codec, } cacher, err := cacherstorage.NewCacherFromConfig(cacherConfig) if err != nil { return nil, func() {}, err } + delegator := cacherstorage.NewCacheDelegator(cacher, s) var once sync.Once destroyFunc := func() { once.Do(func() { + delegator.Stop() cacher.Stop() d() }) } - return cacher, destroyFunc, nil + return delegator, destroyFunc, nil } } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/store.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/store.go index ba64fc367..56e1720f7 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/store.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/generic/registry/store.go @@ -1240,7 +1240,6 @@ func (e *Store) DeleteCollection(ctx context.Context, deleteValidation rest.Vali var items []runtime.Object - // TODO(wojtek-t): Decide if we don't want to start workers more opportunistically. workersNumber := e.DeleteCollectionWorkers if workersNumber < 1 { workersNumber = 1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/delete.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/delete.go index 34102690e..a7e788ba3 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/delete.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/delete.go @@ -126,9 +126,22 @@ func BeforeDelete(strategy RESTDeleteStrategy, ctx context.Context, obj runtime. if period >= *objectMeta.GetDeletionGracePeriodSeconds() { return false, true, nil } + // Move the existing deletionTimestamp back by existing object.DeletionGracePeriod, then forward by options.DeletionGracePeriod. + // This moves the deletionTimestamp back, since the grace period can only be shortened in this code path. newDeletionTimestamp := metav1.NewTime( objectMeta.GetDeletionTimestamp().Add(-time.Second * time.Duration(*objectMeta.GetDeletionGracePeriodSeconds())). Add(time.Second * time.Duration(*options.GracePeriodSeconds))) + // Prevent shortening the grace period moving deletionTimestamp into the past + if now := metav1Now(); newDeletionTimestamp.Before(&now) { + newDeletionTimestamp = now + if period != 0 { + // Since a graceful deletion was requested (options.GracePeriodSeconds != 0), but the entire grace period has already expired, + // shorten to the minimum period possible while still treating this as a graceful delete. + // This means the API server updates the object, another actor observes the update + // and is still responsible for the final delete with options.GracePeriodSeconds == 0. + period = int64(1) + } + } objectMeta.SetDeletionTimestamp(&newDeletionTimestamp) objectMeta.SetDeletionGracePeriodSeconds(&period) return true, false, nil @@ -147,8 +160,8 @@ func BeforeDelete(strategy RESTDeleteStrategy, ctx context.Context, obj runtime. return false, false, errors.NewInternalError(fmt.Errorf("options.GracePeriodSeconds should not be nil")) } - now := metav1.NewTime(metav1.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) - objectMeta.SetDeletionTimestamp(&now) + requestedDeletionTimestamp := metav1.NewTime(metav1Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) + objectMeta.SetDeletionTimestamp(&requestedDeletionTimestamp) objectMeta.SetDeletionGracePeriodSeconds(options.GracePeriodSeconds) // If it's the first graceful deletion we are going to set the DeletionTimestamp to non-nil. // Controllers of the object that's being deleted shouldn't take any nontrivial actions, hence its behavior changes. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/doc.go index 20524d21f..951a6278e 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package rest defines common logic around changes to Kubernetes-style resources. -package rest // import "k8s.io/apiserver/pkg/registry/rest" +package rest diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/meta.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/meta.go index 12c1e5f98..fc4fc81e1 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/meta.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/meta.go @@ -23,6 +23,9 @@ import ( "k8s.io/apimachinery/pkg/util/uuid" ) +// metav1Now returns metav1.Now(), but allows override for unit testing +var metav1Now = func() metav1.Time { return metav1.Now() } + // WipeObjectMetaSystemFields erases fields that are managed by the system on ObjectMeta. func WipeObjectMetaSystemFields(meta metav1.Object) { meta.SetCreationTimestamp(metav1.Time{}) @@ -34,7 +37,7 @@ func WipeObjectMetaSystemFields(meta metav1.Object) { // FillObjectMetaSystemFields populates fields that are managed by the system on ObjectMeta. func FillObjectMetaSystemFields(meta metav1.Object) { - meta.SetCreationTimestamp(metav1.Now()) + meta.SetCreationTimestamp(metav1Now()) meta.SetUID(uuid.NewUUID()) } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/validate.go b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/validate.go new file mode 100644 index 000000000..7f02f1fa4 --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/registry/rest/validate.go @@ -0,0 +1,321 @@ +/* +Copyright 2025 The Kubernetes 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 rest + +import ( + "context" + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/validation/field" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + validationmetrics "k8s.io/apiserver/pkg/validation" + "k8s.io/klog/v2" +) + +// ValidateDeclaratively validates obj against declarative validation tags +// defined in its Go type. It uses the API version extracted from ctx and the +// provided scheme for validation. +// +// The ctx MUST contain requestInfo, which determines the target API for +// validation. The obj is converted to the API version using the provided scheme +// before validation occurs. The scheme MUST have the declarative validation +// registered for the requested resource/subresource. +// +// option should contain any validation options that the declarative validation +// tags expect. +// +// Returns a field.ErrorList containing any validation errors. An internal error +// is included if requestInfo is missing from the context or if version +// conversion fails. +func ValidateDeclaratively(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj runtime.Object) field.ErrorList { + if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found { + groupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion} + versionedObj, err := scheme.ConvertToVersion(obj, groupVersion) + if err != nil { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("unexpected error converting to versioned type: %w", err))} + } + subresources, err := parseSubresourcePath(requestInfo.Subresource) + if err != nil { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("unexpected error parsing subresource path: %w", err))} + } + return scheme.Validate(ctx, options, versionedObj, subresources...) + } else { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("could not find requestInfo in context"))} + } +} + +// ValidateUpdateDeclaratively validates obj and oldObj against declarative +// validation tags defined in its Go type. It uses the API version extracted from +// ctx and the provided scheme for validation. +// +// The ctx MUST contain requestInfo, which determines the target API for +// validation. The obj is converted to the API version using the provided scheme +// before validation occurs. The scheme MUST have the declarative validation +// registered for the requested resource/subresource. +// +// option should contain any validation options that the declarative validation +// tags expect. +// +// Returns a field.ErrorList containing any validation errors. An internal error +// is included if requestInfo is missing from the context or if version +// conversion fails. +func ValidateUpdateDeclaratively(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj, oldObj runtime.Object) field.ErrorList { + if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found { + groupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion} + versionedObj, err := scheme.ConvertToVersion(obj, groupVersion) + if err != nil { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("unexpected error converting to versioned type: %w", err))} + } + versionedOldObj, err := scheme.ConvertToVersion(oldObj, groupVersion) + if err != nil { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("unexpected error converting to versioned type: %w", err))} + } + subresources, err := parseSubresourcePath(requestInfo.Subresource) + if err != nil { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("unexpected error parsing subresource path: %w", err))} + } + return scheme.ValidateUpdate(ctx, options, versionedObj, versionedOldObj, subresources...) + } else { + return field.ErrorList{field.InternalError(nil, fmt.Errorf("could not find requestInfo in context"))} + } +} + +func parseSubresourcePath(subresourcePath string) ([]string, error) { + if len(subresourcePath) == 0 { + return nil, nil + } + parts := strings.Split(subresourcePath, "/") + for _, part := range parts { + if len(part) == 0 { + return nil, fmt.Errorf("invalid subresource path: %s", subresourcePath) + } + } + return parts, nil +} + +// CompareDeclarativeErrorsAndEmitMismatches checks for mismatches between imperative and declarative validation +// and logs + emits metrics when inconsistencies are found +func CompareDeclarativeErrorsAndEmitMismatches(ctx context.Context, imperativeErrs, declarativeErrs field.ErrorList, takeover bool) { + logger := klog.FromContext(ctx) + mismatchDetails := gatherDeclarativeValidationMismatches(imperativeErrs, declarativeErrs, takeover) + for _, detail := range mismatchDetails { + // Log information about the mismatch using contextual logger + logger.Error(nil, detail) + + // Increment the metric for the mismatch + validationmetrics.Metrics.IncDeclarativeValidationMismatchMetric() + } +} + +// gatherDeclarativeValidationMismatches compares imperative and declarative validation errors +// and returns detailed information about any mismatches found. Errors are compared via type, field, and origin +func gatherDeclarativeValidationMismatches(imperativeErrs, declarativeErrs field.ErrorList, takeover bool) []string { + var mismatchDetails []string + // short circuit here to minimize allocs for usual case of 0 validation errors + if len(imperativeErrs) == 0 && len(declarativeErrs) == 0 { + return mismatchDetails + } + // recommendation based on takeover status + recommendation := "This difference should not affect system operation since hand written validation is authoritative." + if takeover { + recommendation = "Consider disabling the DeclarativeValidationTakeover feature gate to keep data persisted in etcd consistent with prior versions of Kubernetes." + } + fuzzyMatcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin().RequireOriginWhenInvalid() + exactMatcher := field.ErrorMatcher{}.Exactly() + + // Dedupe imperative errors of exact error matches as they are + // not intended and come from (buggy) duplicate validation calls + // This is necessary as without deduping we could get unmatched + // imperative errors for cases that are correct (matching) + dedupedImperativeErrs := field.ErrorList{} + for _, err := range imperativeErrs { + found := false + for _, existingErr := range dedupedImperativeErrs { + if exactMatcher.Matches(existingErr, err) { + found = true + break + } + } + if !found { + dedupedImperativeErrs = append(dedupedImperativeErrs, err) + } + } + imperativeErrs = dedupedImperativeErrs + + // Create a copy of declarative errors to track remaining ones + remaining := make(field.ErrorList, len(declarativeErrs)) + copy(remaining, declarativeErrs) + + // Match each "covered" imperative error to declarative errors. + // We use a fuzzy matching approach to find corresponding declarative errors + // for each imperative error marked as CoveredByDeclarative. + // As matches are found, they're removed from the 'remaining' list. + // They are removed from `remaining` with a "1:many" mapping: for a given + // imperative error we mark as matched all matching declarative errors + // This allows us to: + // 1. Detect imperative errors that should have matching declarative errors but don't + // 2. Identify extra declarative errors with no imperative counterpart + // Both cases indicate issues with the declarative validation implementation. + for _, iErr := range imperativeErrs { + if !iErr.CoveredByDeclarative { + continue + } + + tmp := make(field.ErrorList, 0, len(remaining)) + matchCount := 0 + + for _, dErr := range remaining { + if fuzzyMatcher.Matches(iErr, dErr) { + matchCount++ + } else { + tmp = append(tmp, dErr) + } + } + + if matchCount == 0 { + mismatchDetails = append(mismatchDetails, + fmt.Sprintf( + "Unexpected difference between hand written validation and declarative validation error results, unmatched error(s) found %s. "+ + "This indicates an issue with declarative validation. %s", + fuzzyMatcher.Render(iErr), + recommendation, + ), + ) + } + + remaining = tmp + } + + // Any remaining unmatched declarative errors are considered "extra" + for _, dErr := range remaining { + mismatchDetails = append(mismatchDetails, + fmt.Sprintf( + "Unexpected difference between hand written validation and declarative validation error results, extra error(s) found %s. "+ + "This indicates an issue with declarative validation. %s", + fuzzyMatcher.Render(dErr), + recommendation, + ), + ) + } + + return mismatchDetails +} + +// createDeclarativeValidationPanicHandler returns a function with panic recovery logic +// that will increment the panic metric and either log or append errors based on the takeover parameter. +func createDeclarativeValidationPanicHandler(ctx context.Context, errs *field.ErrorList, takeover bool) func() { + logger := klog.FromContext(ctx) + return func() { + if r := recover(); r != nil { + // Increment the panic metric counter + validationmetrics.Metrics.IncDeclarativeValidationPanicMetric() + + const errorFmt = "panic during declarative validation: %v" + if takeover { + // If takeover is enabled, output as a validation error as authoritative validator panicked and validation should error + *errs = append(*errs, field.InternalError(nil, fmt.Errorf(errorFmt, r))) + } else { + // if takeover not enabled, log the panic as an error message + logger.Error(nil, fmt.Sprintf(errorFmt, r)) + } + } + } +} + +// panicSafeValidateFunc wraps a validation function with panic recovery logic. +// It takes a validation function with the ValidateDeclaratively signature +// and returns a function with the same signature. +// The returned function will execute the wrapped function and handle any panics by +// incrementing the panic metric, and logging an error message +// if takeover=false, and adding a validation error if takeover=true. +func panicSafeValidateFunc( + validateFunc func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj runtime.Object) field.ErrorList, + takeover bool, +) func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj runtime.Object) field.ErrorList { + return func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj runtime.Object) (errs field.ErrorList) { + defer createDeclarativeValidationPanicHandler(ctx, &errs, takeover)() + + return validateFunc(ctx, options, scheme, obj) + } +} + +// panicSafeValidateUpdateFunc wraps an update validation function with panic recovery logic. +// It takes a validation function with the ValidateUpdateDeclaratively signature +// and returns a function with the same signature. +// The returned function will execute the wrapped function and handle any panics by +// incrementing the panic metric, and logging an error message +// if takeover=false, and adding a validation error if takeover=true. +func panicSafeValidateUpdateFunc( + validateUpdateFunc func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj, oldObj runtime.Object) field.ErrorList, + takeover bool, +) func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj, oldObj runtime.Object) field.ErrorList { + return func(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj, oldObj runtime.Object) (errs field.ErrorList) { + defer createDeclarativeValidationPanicHandler(ctx, &errs, takeover)() + + return validateUpdateFunc(ctx, options, scheme, obj, oldObj) + } +} + +// ValidateDeclarativelyWithRecovery validates obj against declarative validation tags +// with panic recovery logic. It uses the API version extracted from ctx and the +// provided scheme for validation. +// +// The ctx MUST contain requestInfo, which determines the target API for +// validation. The obj is converted to the API version using the provided scheme +// before validation occurs. The scheme MUST have the declarative validation +// registered for the requested resource/subresource. +// +// option should contain any validation options that the declarative validation +// tags expect. +// +// takeover determines if panic recovery should return validation errors (true) or +// just log warnings (false). +// +// Returns a field.ErrorList containing any validation errors. An internal error +// is included if requestInfo is missing from the context, if version +// conversion fails, or if a panic occurs during validation when +// takeover is true. +func ValidateDeclarativelyWithRecovery(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj runtime.Object, takeover bool) field.ErrorList { + return panicSafeValidateFunc(ValidateDeclaratively, takeover)(ctx, options, scheme, obj) +} + +// ValidateUpdateDeclarativelyWithRecovery validates obj and oldObj against declarative +// validation tags with panic recovery logic. It uses the API version extracted from +// ctx and the provided scheme for validation. +// +// The ctx MUST contain requestInfo, which determines the target API for +// validation. The obj is converted to the API version using the provided scheme +// before validation occurs. The scheme MUST have the declarative validation +// registered for the requested resource/subresource. +// +// option should contain any validation options that the declarative validation +// tags expect. +// +// takeover determines if panic recovery should return validation errors (true) or +// just log warnings (false). +// +// Returns a field.ErrorList containing any validation errors. An internal error +// is included if requestInfo is missing from the context, if version +// conversion fails, or if a panic occurs during validation when +// takeover is true. +func ValidateUpdateDeclarativelyWithRecovery(ctx context.Context, options sets.Set[string], scheme *runtime.Scheme, obj, oldObj runtime.Object, takeover bool) field.ErrorList { + return panicSafeValidateUpdateFunc(ValidateUpdateDeclaratively, takeover)(ctx, options, scheme, obj, oldObj) +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/config.go b/e2e/vendor/k8s.io/apiserver/pkg/server/config.go index ee037aefe..3e8a6b8c0 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/config.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/config.go @@ -73,12 +73,12 @@ import ( flowcontrolrequest "k8s.io/apiserver/pkg/util/flowcontrol/request" "k8s.io/client-go/informers" restclient "k8s.io/client-go/rest" + basecompatibility "k8s.io/component-base/compatibility" "k8s.io/component-base/featuregate" "k8s.io/component-base/logs" "k8s.io/component-base/metrics/features" "k8s.io/component-base/metrics/prometheus/slis" "k8s.io/component-base/tracing" - utilversion "k8s.io/component-base/version" "k8s.io/component-base/zpages/flagz" "k8s.io/klog/v2" openapicommon "k8s.io/kube-openapi/pkg/common" @@ -153,7 +153,17 @@ type Config struct { // EffectiveVersion determines which apis and features are available // based on when the api/feature lifecyle. - EffectiveVersion utilversion.EffectiveVersion + EffectiveVersion basecompatibility.EffectiveVersion + // EmulationForwardCompatible is an option to implicitly enable all APIs which are introduced after the emulation version and + // have higher priority than APIs of the same group resource enabled at the emulation version. + // If true, all APIs that have higher priority than the APIs(beta+) of the same group resource enabled at the emulation version will be installed. + // This is needed when a controller implementation migrates to newer API versions, for the binary version, and also uses the newer API versions even when emulation version is set. + // Not applicable to alpha APIs. + EmulationForwardCompatible bool + // RuntimeConfigEmulationForwardCompatible is an option to explicitly enable specific APIs introduced after the emulation version through the runtime-config. + // If true, APIs identified by group/version that are enabled in the --runtime-config flag will be installed even if it is introduced after the emulation version. --runtime-config flag values that identify multiple APIs, such as api/all,api/ga,api/beta, are not influenced by this flag and will only enable APIs available at the current emulation version. + // If false, error would be thrown if any GroupVersion or GroupVersionResource explicitly enabled in the --runtime-config flag is introduced after the emulation version. + RuntimeConfigEmulationForwardCompatible bool // FeatureGate is a way to plumb feature gate through if you have them. FeatureGate featuregate.FeatureGate // AuditBackend is where audit events are sent to. @@ -839,20 +849,20 @@ func (c completedConfig) New(name string, delegationTarget DelegationTarget) (*G StorageReadinessHook: NewStorageReadinessHook(c.StorageInitializationTimeout), StorageVersionManager: c.StorageVersionManager, - EffectiveVersion: c.EffectiveVersion, - FeatureGate: c.FeatureGate, + EffectiveVersion: c.EffectiveVersion, + EmulationForwardCompatible: c.EmulationForwardCompatible, + RuntimeConfigEmulationForwardCompatible: c.RuntimeConfigEmulationForwardCompatible, + FeatureGate: c.FeatureGate, muxAndDiscoveryCompleteSignals: map[string]<-chan struct{}{}, } - if c.FeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) { - manager := c.AggregatedDiscoveryGroupManager - if manager == nil { - manager = discoveryendpoint.NewResourceManager("apis") - } - s.AggregatedDiscoveryGroupManager = manager - s.AggregatedLegacyDiscoveryGroupManager = discoveryendpoint.NewResourceManager("api") + manager := c.AggregatedDiscoveryGroupManager + if manager == nil { + manager = discoveryendpoint.NewResourceManager("apis") } + s.AggregatedDiscoveryGroupManager = manager + s.AggregatedLegacyDiscoveryGroupManager = discoveryendpoint.NewResourceManager("api") for { if c.JSONPatchMaxCopyBytes <= 0 { break @@ -1030,6 +1040,11 @@ func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler { failedHandler := genericapifilters.Unauthorized(c.Serializer) failedHandler = genericapifilters.WithFailedAuthenticationAudit(failedHandler, c.AuditBackend, c.AuditPolicyRuleEvaluator) + // WithTracing comes after authentication so we can allow authenticated + // clients to influence sampling. + if c.FeatureGate.Enabled(genericfeatures.APIServerTracing) { + handler = genericapifilters.WithTracing(handler, c.TracerProvider) + } failedHandler = filterlatency.TrackCompleted(failedHandler) handler = filterlatency.TrackCompleted(handler) handler = genericapifilters.WithAuthentication(handler, c.Authentication.Authenticator, failedHandler, c.Authentication.APIAudiences, c.Authentication.RequestHeaderConfig) @@ -1060,9 +1075,6 @@ func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler { handler = genericfilters.WithRetryAfter(handler, c.lifecycleSignals.NotAcceptingNewRequest.Signaled()) } handler = genericfilters.WithHTTPLogging(handler) - if c.FeatureGate.Enabled(genericfeatures.APIServerTracing) { - handler = genericapifilters.WithTracing(handler, c.TracerProvider) - } handler = genericapifilters.WithLatencyTrackers(handler) // WithRoutine will execute future handlers in a separate goroutine and serving // handler in current goroutine to minimize the stack memory usage. It must be @@ -1108,15 +1120,11 @@ func installAPI(name string, s *GenericAPIServer, c *Config) { } } - routes.Version{Version: c.EffectiveVersion.BinaryVersion().Info()}.Install(s.Handler.GoRestfulContainer) + routes.Version{Version: c.EffectiveVersion.Info()}.Install(s.Handler.GoRestfulContainer) if c.EnableDiscovery { - if c.FeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) { - wrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(s.DiscoveryGroupManager, s.AggregatedDiscoveryGroupManager) - s.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService("/apis", metav1.APIGroupList{})) - } else { - s.Handler.GoRestfulContainer.Add(s.DiscoveryGroupManager.WebService()) - } + wrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(s.DiscoveryGroupManager, s.AggregatedDiscoveryGroupManager) + s.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService("/apis", metav1.APIGroupList{})) } if c.FlowControl != nil { c.FlowControl.Install(s.Handler.NonGoRestfulMux) diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/deleted_kinds.go b/e2e/vendor/k8s.io/apiserver/pkg/server/deleted_kinds.go index 28cc0bf05..1b94b5613 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/deleted_kinds.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/deleted_kinds.go @@ -19,6 +19,8 @@ package server import ( "fmt" "os" + "regexp" + "sort" "strconv" "strings" @@ -27,16 +29,26 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" apimachineryversion "k8s.io/apimachinery/pkg/util/version" + "k8s.io/apimachinery/pkg/version" "k8s.io/apiserver/pkg/registry/rest" + serverstorage "k8s.io/apiserver/pkg/server/storage" "k8s.io/klog/v2" ) +var alphaPattern = regexp.MustCompile(`^v\d+alpha\d+$`) + // resourceExpirationEvaluator holds info for deciding if a particular rest.Storage needs to excluded from the API type resourceExpirationEvaluator struct { - currentVersion *apimachineryversion.Version - isAlpha bool + currentVersion *apimachineryversion.Version + emulationForwardCompatible bool + runtimeConfigEmulationForwardCompatible bool + isAlpha bool + // Special flag checking for the existence of alpha.0 + // alpha.0 is a special case where everything merged to master is auto propagated to the release-1.n branch + isAlphaZero bool // This is usually set for testing for which tests need to be removed. This prevent insta-failing CI. // Set KUBE_APISERVER_STRICT_REMOVED_API_HANDLING_IN_ALPHA to see what will be removed when we tag beta + // This flag only takes effect during alpha but not alphaZero. strictRemovedHandlingInAlpha bool // This is usually set by a cluster-admin looking for a short-term escape hatch after something bad happened. // This should be made a flag before merge @@ -46,24 +58,51 @@ type resourceExpirationEvaluator struct { // ResourceExpirationEvaluator indicates whether or not a resource should be served. type ResourceExpirationEvaluator interface { - // RemoveDeletedKinds inspects the storage map and modifies it in place by removing storage for kinds that have been deleted. + // RemoveUnavailableKinds inspects the storage map and modifies it in place by removing storage for kinds that have been deleted or are introduced after the current version. // versionedResourcesStorageMap mirrors the field on APIGroupInfo, it's a map from version to resource to the storage. - RemoveDeletedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage) + RemoveUnavailableKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage, apiResourceConfigSource serverstorage.APIResourceConfigSource) error // ShouldServeForVersion returns true if a particular version cut off is after the current version ShouldServeForVersion(majorRemoved, minorRemoved int) bool } +type ResourceExpirationEvaluatorOptions struct { + // CurrentVersion is the current version of the apiserver. + CurrentVersion *apimachineryversion.Version + // Prerelease holds an optional prerelease portion of the version. + // This is used to determine if the current binary is an alpha. + Prerelease string + // EmulationForwardCompatible indicates whether the apiserver should serve resources that are introduced after the current version, + // when resources of the same group and resource name but with lower priority are served. + // Not applicable to alpha APIs. + EmulationForwardCompatible bool + // RuntimeConfigEmulationForwardCompatible indicates whether the apiserver should serve resources that are introduced after the current version, + // when the resource is explicitly enabled in runtime-config. + RuntimeConfigEmulationForwardCompatible bool +} + func NewResourceExpirationEvaluator(currentVersion *apimachineryversion.Version) (ResourceExpirationEvaluator, error) { + opts := ResourceExpirationEvaluatorOptions{ + CurrentVersion: apimachineryversion.MajorMinor(currentVersion.Major(), currentVersion.Minor()), + Prerelease: currentVersion.PreRelease(), + } + return NewResourceExpirationEvaluatorFromOptions(opts) +} + +func NewResourceExpirationEvaluatorFromOptions(opts ResourceExpirationEvaluatorOptions) (ResourceExpirationEvaluator, error) { + currentVersion := opts.CurrentVersion if currentVersion == nil { return nil, fmt.Errorf("empty NewResourceExpirationEvaluator currentVersion") } klog.V(1).Infof("NewResourceExpirationEvaluator with currentVersion: %s.", currentVersion) ret := &resourceExpirationEvaluator{ - strictRemovedHandlingInAlpha: false, + strictRemovedHandlingInAlpha: false, + emulationForwardCompatible: opts.EmulationForwardCompatible, + runtimeConfigEmulationForwardCompatible: opts.RuntimeConfigEmulationForwardCompatible, } // Only keeps the major and minor versions from input version. ret.currentVersion = apimachineryversion.MajorMinor(currentVersion.Major(), currentVersion.Minor()) - ret.isAlpha = strings.Contains(currentVersion.PreRelease(), "alpha") + ret.isAlpha = strings.Contains(opts.Prerelease, "alpha") + ret.isAlphaZero = strings.Contains(opts.Prerelease, "alpha.0") if envString, ok := os.LookupEnv("KUBE_APISERVER_STRICT_REMOVED_API_HANDLING_IN_ALPHA"); !ok { // do nothing @@ -84,7 +123,8 @@ func NewResourceExpirationEvaluator(currentVersion *apimachineryversion.Version) return ret, nil } -func (e *resourceExpirationEvaluator) shouldServe(gv schema.GroupVersion, versioner runtime.ObjectVersioner, resourceServingInfo rest.Storage) bool { +// isNotRemoved checks if a resource is removed due to the APILifecycleRemoved information. +func (e *resourceExpirationEvaluator) isNotRemoved(gv schema.GroupVersion, versioner runtime.ObjectVersioner, resourceServingInfo rest.Storage) bool { internalPtr := resourceServingInfo.New() target := gv @@ -99,15 +139,6 @@ func (e *resourceExpirationEvaluator) shouldServe(gv schema.GroupVersion, versio return false } - introduced, ok := versionedPtr.(introducedInterface) - if ok { - majorIntroduced, minorIntroduced := introduced.APILifecycleIntroduced() - verIntroduced := apimachineryversion.MajorMinor(uint(majorIntroduced), uint(minorIntroduced)) - if e.currentVersion.LessThan(verIntroduced) { - return false - } - } - removed, ok := versionedPtr.(removedInterface) if !ok { return true @@ -127,7 +158,7 @@ func (e *resourceExpirationEvaluator) ShouldServeForVersion(majorRemoved, minorR // at this point major and minor are equal, so this API should be removed when the current release GAs. // If this is an alpha tag, don't remove by default, but allow the option. // If the cluster-admin has requested serving one more release, allow it. - if e.isAlpha && e.strictRemovedHandlingInAlpha { // don't serve in alpha if we want strict handling + if e.isAlpha && !e.isAlphaZero && e.strictRemovedHandlingInAlpha { // don't serve in alpha.1+ if we want strict handling return false } if e.isAlpha { // alphas are allowed to continue serving expired betas while we clean up the test @@ -150,13 +181,13 @@ type introducedInterface interface { // removeDeletedKinds inspects the storage map and modifies it in place by removing storage for kinds that have been deleted. // versionedResourcesStorageMap mirrors the field on APIGroupInfo, it's a map from version to resource to the storage. -func (e *resourceExpirationEvaluator) RemoveDeletedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage) { +func (e *resourceExpirationEvaluator) removeDeletedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage) { versionsToRemove := sets.NewString() for apiVersion := range sets.StringKeySet(versionedResourcesStorageMap) { versionToResource := versionedResourcesStorageMap[apiVersion] resourcesToRemove := sets.NewString() for resourceName, resourceServingInfo := range versionToResource { - if !e.shouldServe(schema.GroupVersion{Group: groupName, Version: apiVersion}, versioner, resourceServingInfo) { + if !e.isNotRemoved(schema.GroupVersion{Group: groupName, Version: apiVersion}, versioner, resourceServingInfo) { resourcesToRemove.Insert(resourceName) } } @@ -184,6 +215,126 @@ func (e *resourceExpirationEvaluator) RemoveDeletedKinds(groupName string, versi } } +func (e *resourceExpirationEvaluator) RemoveUnavailableKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage, apiResourceConfigSource serverstorage.APIResourceConfigSource) error { + e.removeDeletedKinds(groupName, versioner, versionedResourcesStorageMap) + return e.removeUnintroducedKinds(groupName, versioner, versionedResourcesStorageMap, apiResourceConfigSource) +} + +// removeUnintroducedKinds inspects the storage map and modifies it in place by removing storage for kinds that are introduced after the current version. +// versionedResourcesStorageMap mirrors the field on APIGroupInfo, it's a map from version to resource to the storage. +func (e *resourceExpirationEvaluator) removeUnintroducedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage, apiResourceConfigSource serverstorage.APIResourceConfigSource) error { + versionsToRemove := sets.NewString() + prioritizedVersions := versioner.PrioritizedVersionsForGroup(groupName) + sort.Slice(prioritizedVersions, func(i, j int) bool { + return version.CompareKubeAwareVersionStrings(prioritizedVersions[i].Version, prioritizedVersions[j].Version) > 0 + }) + enabledResources := sets.NewString() + + // iterate from the end to the front, so that we remove the lower priority versions first. + for i := len(prioritizedVersions) - 1; i >= 0; i-- { + apiVersion := prioritizedVersions[i].Version + versionToResource := versionedResourcesStorageMap[apiVersion] + if len(versionToResource) == 0 { + continue + } + resourcesToRemove := sets.NewString() + for resourceName, resourceServingInfo := range versionToResource { + // we check the resource enablement from low priority to high priority. + // If the same resource with a different version that we have checked so far is already enabled, that means some resource with the same resourceName and a lower priority version has been enabled. + // Then emulation forward compatibility for the version being checked now is made based on this information. + lowerPriorityEnabled := enabledResources.Has(resourceName) + shouldKeep, err := e.shouldServeBasedOnVersionIntroduced(schema.GroupVersionResource{Group: groupName, Version: apiVersion, Resource: resourceName}, + versioner, resourceServingInfo, apiResourceConfigSource, lowerPriorityEnabled) + if err != nil { + return err + } + if !shouldKeep { + resourcesToRemove.Insert(resourceName) + } else if !alphaPattern.MatchString(apiVersion) { + // enabledResources is passed onto the next iteration to check the enablement of higher priority resources for emulation forward compatibility. + // But enablement alpha apis do not affect the enablement of other versions because emulation forward compatibility is not applicable to alpha apis. + enabledResources.Insert(resourceName) + } + } + + for resourceName := range versionedResourcesStorageMap[apiVersion] { + if !shouldRemoveResourceAndSubresources(resourcesToRemove, resourceName) { + continue + } + + klog.V(1).Infof("Removing resource %v.%v.%v because it is introduced after the current version %s per APILifecycle.", resourceName, apiVersion, groupName, e.currentVersion.String()) + storage := versionToResource[resourceName] + storage.Destroy() + delete(versionToResource, resourceName) + } + versionedResourcesStorageMap[apiVersion] = versionToResource + + if len(versionedResourcesStorageMap[apiVersion]) == 0 { + versionsToRemove.Insert(apiVersion) + } + } + + for _, apiVersion := range versionsToRemove.List() { + gv := schema.GroupVersion{Group: groupName, Version: apiVersion} + if apiResourceConfigSource != nil && apiResourceConfigSource.VersionExplicitlyEnabled(gv) { + return fmt.Errorf( + "cannot enable version %s in runtime-config because all the resources have been introduced after the current version %s. Consider setting --runtime-config-emulation-forward-compatible=true", + gv, e.currentVersion) + } + klog.V(1).Infof("Removing version %v.%v because it is introduced after the current version %s and because it has no resources per APILifecycle.", apiVersion, groupName, e.currentVersion.String()) + delete(versionedResourcesStorageMap, apiVersion) + } + return nil +} + +func (e *resourceExpirationEvaluator) shouldServeBasedOnVersionIntroduced(gvr schema.GroupVersionResource, versioner runtime.ObjectVersioner, resourceServingInfo rest.Storage, + apiResourceConfigSource serverstorage.APIResourceConfigSource, lowerPriorityEnabled bool) (bool, error) { + verIntroduced := apimachineryversion.MajorMinor(0, 0) + internalPtr := resourceServingInfo.New() + + target := gvr.GroupVersion() + // honor storage that overrides group version (used for things like scale subresources) + if versionProvider, ok := resourceServingInfo.(rest.GroupVersionKindProvider); ok { + target = versionProvider.GroupVersionKind(target).GroupVersion() + } + + versionedPtr, err := versioner.ConvertToVersion(internalPtr, target) + if err != nil { + utilruntime.HandleError(err) + return false, err + } + + introduced, ok := versionedPtr.(introducedInterface) + if ok { + majorIntroduced, minorIntroduced := introduced.APILifecycleIntroduced() + verIntroduced = apimachineryversion.MajorMinor(uint(majorIntroduced), uint(minorIntroduced)) + } + // should serve resource introduced at or before the current version. + if e.currentVersion.AtLeast(verIntroduced) { + return true, nil + } + // the rest of the function is to determine if a resource introduced after current version should be served. (only applicable in emulation mode.) + + // if a lower priority version of the resource has been enabled, the same resource with higher priority + // should also be enabled if emulationForwardCompatible = true. + if e.emulationForwardCompatible && lowerPriorityEnabled { + return true, nil + } + if apiResourceConfigSource == nil { + return false, nil + } + // could explicitly enable future resources in runtime-config forward compatible mode. + if e.runtimeConfigEmulationForwardCompatible && (apiResourceConfigSource.ResourceExplicitlyEnabled(gvr) || apiResourceConfigSource.VersionExplicitlyEnabled(gvr.GroupVersion())) { + return true, nil + } + // return error if a future resource is explicit enabled in runtime-config but runtimeConfigEmulationForwardCompatible is false. + if apiResourceConfigSource.ResourceExplicitlyEnabled(gvr) { + return false, fmt.Errorf("cannot enable resource %s in runtime-config because it is introduced at %s after the current version %s. Consider setting --runtime-config-emulation-forward-compatible=true", + gvr, verIntroduced, e.currentVersion) + } + return false, nil +} + func shouldRemoveResourceAndSubresources(resourcesToRemove sets.String, resourceName string) bool { for _, resourceToRemove := range resourcesToRemove.List() { if resourceName == resourceToRemove { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/doc.go index bc671eae8..b5f97c658 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package server contains the plumbing to create kubernetes-like API server command. -package server // import "k8s.io/apiserver/pkg/server" +package server diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/filters/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/filters/doc.go index a90cc3b49..9fe0b2c35 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/filters/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/filters/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package filters contains all the http handler chain filters which // are not api related. -package filters // import "k8s.io/apiserver/pkg/server/filters" +package filters diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go b/e2e/vendor/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go index decd9d6ca..5986993d4 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go @@ -52,8 +52,8 @@ var waitingMark = &requestWatermark{ phase: epmetrics.WaitingPhase, } -var atomicMutatingExecuting, atomicReadOnlyExecuting int32 -var atomicMutatingWaiting, atomicReadOnlyWaiting int32 +var atomicMutatingExecuting, atomicReadOnlyExecuting atomic.Int32 +var atomicMutatingWaiting, atomicReadOnlyWaiting atomic.Int32 // newInitializationSignal is defined for testing purposes. var newInitializationSignal = utilflowcontrol.NewInitializationSignal @@ -143,16 +143,16 @@ func (h *priorityAndFairnessHandler) Handle(w http.ResponseWriter, r *http.Reque isMutatingRequest := !nonMutatingRequestVerbs.Has(requestInfo.Verb) noteExecutingDelta := func(delta int32) { if isMutatingRequest { - watermark.recordMutating(int(atomic.AddInt32(&atomicMutatingExecuting, delta))) + watermark.recordMutating(int(atomicMutatingExecuting.Add(delta))) } else { - watermark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyExecuting, delta))) + watermark.recordReadOnly(int(atomicReadOnlyExecuting.Add(delta))) } } noteWaitingDelta := func(delta int32) { if isMutatingRequest { - waitingMark.recordMutating(int(atomic.AddInt32(&atomicMutatingWaiting, delta))) + waitingMark.recordMutating(int(atomicMutatingWaiting.Add(delta))) } else { - waitingMark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyWaiting, delta))) + waitingMark.recordReadOnly(int(atomicReadOnlyWaiting.Add(delta))) } } queueNote := func(inQueue bool) { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/genericapiserver.go b/e2e/vendor/k8s.io/apiserver/pkg/server/genericapiserver.go index e810a4608..a0ff71b9b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/genericapiserver.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/genericapiserver.go @@ -54,8 +54,8 @@ import ( "k8s.io/apiserver/pkg/storageversion" utilfeature "k8s.io/apiserver/pkg/util/feature" restclient "k8s.io/client-go/rest" + basecompatibility "k8s.io/component-base/compatibility" "k8s.io/component-base/featuregate" - utilversion "k8s.io/component-base/version" "k8s.io/klog/v2" openapibuilder3 "k8s.io/kube-openapi/pkg/builder3" openapicommon "k8s.io/kube-openapi/pkg/common" @@ -244,7 +244,18 @@ type GenericAPIServer struct { // EffectiveVersion determines which apis and features are available // based on when the api/feature lifecyle. - EffectiveVersion utilversion.EffectiveVersion + EffectiveVersion basecompatibility.EffectiveVersion + // EmulationForwardCompatible is an option to implicitly enable all APIs which are introduced after the emulation version and + // have higher priority than APIs of the same group resource enabled at the emulation version. + // If true, all APIs that have higher priority than the APIs(beta+) of the same group resource enabled at the emulation version will be installed. + // This is needed when a controller implementation migrates to newer API versions, for the binary version, and also uses the newer API versions even when emulation version is set. + // Not applicable to alpha APIs. + EmulationForwardCompatible bool + // RuntimeConfigEmulationForwardCompatible is an option to explicitly enable specific APIs introduced after the emulation version through the runtime-config. + // If true, APIs identified by group/version that are enabled in the --runtime-config flag will be installed even if it is introduced after the emulation version. --runtime-config flag values that identify multiple APIs, such as api/all,api/ga,api/beta, are not influenced by this flag and will only enable APIs available at the current emulation version. + // If false, error would be thrown if any GroupVersion or GroupVersionResource explicitly enabled in the --runtime-config flag is introduced after the emulation version. + RuntimeConfigEmulationForwardCompatible bool + // FeatureGate is a way to plumb feature gate through if you have them. FeatureGate featuregate.FeatureGate @@ -785,28 +796,26 @@ func (s *GenericAPIServer) installAPIResources(apiPrefix string, apiGroupInfo *A } resourceInfos = append(resourceInfos, r...) - if s.FeatureGate.Enabled(features.AggregatedDiscoveryEndpoint) { - // Aggregated discovery only aggregates resources under /apis - if apiPrefix == APIGroupPrefix { - s.AggregatedDiscoveryGroupManager.AddGroupVersion( - groupVersion.Group, - apidiscoveryv2.APIVersionDiscovery{ - Freshness: apidiscoveryv2.DiscoveryFreshnessCurrent, - Version: groupVersion.Version, - Resources: discoveryAPIResources, - }, - ) - } else { - // There is only one group version for legacy resources, priority can be defaulted to 0. - s.AggregatedLegacyDiscoveryGroupManager.AddGroupVersion( - groupVersion.Group, - apidiscoveryv2.APIVersionDiscovery{ - Freshness: apidiscoveryv2.DiscoveryFreshnessCurrent, - Version: groupVersion.Version, - Resources: discoveryAPIResources, - }, - ) - } + // Aggregated discovery only aggregates resources under /apis + if apiPrefix == APIGroupPrefix { + s.AggregatedDiscoveryGroupManager.AddGroupVersion( + groupVersion.Group, + apidiscoveryv2.APIVersionDiscovery{ + Freshness: apidiscoveryv2.DiscoveryFreshnessCurrent, + Version: groupVersion.Version, + Resources: discoveryAPIResources, + }, + ) + } else { + // There is only one group version for legacy resources, priority can be defaulted to 0. + s.AggregatedLegacyDiscoveryGroupManager.AddGroupVersion( + groupVersion.Group, + apidiscoveryv2.APIVersionDiscovery{ + Freshness: apidiscoveryv2.DiscoveryFreshnessCurrent, + Version: groupVersion.Version, + Resources: discoveryAPIResources, + }, + ) } } @@ -844,12 +853,8 @@ func (s *GenericAPIServer) InstallLegacyAPIGroup(apiPrefix string, apiGroupInfo // Install the version handler. // Add a handler at / to enumerate the supported api versions. legacyRootAPIHandler := discovery.NewLegacyRootAPIHandler(s.discoveryAddresses, s.Serializer, apiPrefix) - if s.FeatureGate.Enabled(features.AggregatedDiscoveryEndpoint) { - wrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(legacyRootAPIHandler, s.AggregatedLegacyDiscoveryGroupManager) - s.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService("/api", metav1.APIVersions{})) - } else { - s.Handler.GoRestfulContainer.Add(legacyRootAPIHandler.WebService()) - } + wrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(legacyRootAPIHandler, s.AggregatedLegacyDiscoveryGroupManager) + s.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService("/api", metav1.APIVersions{})) s.registerStorageReadinessCheck("", apiGroupInfo) return nil @@ -991,8 +996,18 @@ func (s *GenericAPIServer) newAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupV // NewDefaultAPIGroupInfo returns an APIGroupInfo stubbed with "normal" values // exposed for easier composition from other packages func NewDefaultAPIGroupInfo(group string, scheme *runtime.Scheme, parameterCodec runtime.ParameterCodec, codecs serializer.CodecFactory) APIGroupInfo { + opts := []serializer.CodecFactoryOptionsMutator{} if utilfeature.DefaultFeatureGate.Enabled(features.CBORServingAndStorage) { - codecs = serializer.NewCodecFactory(scheme, serializer.WithSerializer(cbor.NewSerializerInfo)) + opts = append(opts, serializer.WithSerializer(cbor.NewSerializerInfo)) + } + if utilfeature.DefaultFeatureGate.Enabled(features.StreamingCollectionEncodingToJSON) { + opts = append(opts, serializer.WithStreamingCollectionEncodingToJSON()) + } + if utilfeature.DefaultFeatureGate.Enabled(features.StreamingCollectionEncodingToProtobuf) { + opts = append(opts, serializer.WithStreamingCollectionEncodingToProtobuf()) + } + if len(opts) != 0 { + codecs = serializer.NewCodecFactory(scheme, opts...) } return APIGroupInfo{ PrioritizedVersions: scheme.PrioritizedVersionsForGroup(group), diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/healthz/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/healthz/doc.go index ad3f00187..3881c0940 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/healthz/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/healthz/doc.go @@ -19,4 +19,4 @@ limitations under the License. // // import "k8s.io/apiserver/pkg/server/healthz" // healthz.InstallHandler(mux) -package healthz // import "k8s.io/apiserver/pkg/server/healthz" +package healthz diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/httplog/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/httplog/doc.go index caa6572c7..57aa55ab9 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/httplog/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/httplog/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package httplog contains a helper object and functions to maintain a log // along with an http response. -package httplog // import "k8s.io/apiserver/pkg/server/httplog" +package httplog diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/mux/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/mux/doc.go index 178aa9fe6..da9fb8ed7 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/mux/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/mux/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package mux contains abstractions for http multiplexing of APIs. -package mux // import "k8s.io/apiserver/pkg/server/mux" +package mux diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/options/api_enablement.go b/e2e/vendor/k8s.io/apiserver/pkg/server/options/api_enablement.go index 6ab58bab2..d5b518b05 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/options/api_enablement.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/options/api_enablement.go @@ -95,6 +95,14 @@ func (s *APIEnablementOptions) ApplyTo(c *server.Config, defaultResourceConfig * } mergedResourceConfig, err := resourceconfig.MergeAPIResourceConfigs(defaultResourceConfig, s.RuntimeConfig, registry) + if err != nil { + return err + } + // apply emulation forward compatibility to the api enablement if applicable. + if c.EmulationForwardCompatible { + mergedResourceConfig, err = resourceconfig.EmulationForwardCompatibleResourceConfig(mergedResourceConfig, s.RuntimeConfig, registry) + } + c.MergedResourceConfig = mergedResourceConfig return err diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/options/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/options/doc.go index 426336be0..a7167a419 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/options/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/options/doc.go @@ -18,4 +18,4 @@ limitations under the License. // server. It takes a minimal set of dependencies and does not reference // implementations, in order to ensure it may be reused by multiple components // (such as CLI commands that wish to generate or validate config). -package options // import "k8s.io/apiserver/pkg/server/options" +package options diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go b/e2e/vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go index a4d31ef92..d4032fd21 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go @@ -27,9 +27,9 @@ import ( "k8s.io/apimachinery/pkg/util/errors" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apiserver/pkg/server" + "k8s.io/apiserver/pkg/util/compatibility" utilfeature "k8s.io/apiserver/pkg/util/feature" - "k8s.io/component-base/featuregate" - utilversion "k8s.io/component-base/version" + basecompatibility "k8s.io/component-base/compatibility" "github.com/spf13/pflag" ) @@ -95,22 +95,32 @@ type ServerRunOptions struct { ShutdownWatchTerminationGracePeriod time.Duration // ComponentGlobalsRegistry is the registry where the effective versions and feature gates for all components are stored. - ComponentGlobalsRegistry featuregate.ComponentGlobalsRegistry + ComponentGlobalsRegistry basecompatibility.ComponentGlobalsRegistry // ComponentName is name under which the server's global variabled are registered in the ComponentGlobalsRegistry. ComponentName string + // EmulationForwardCompatible is an option to implicitly enable all APIs which are introduced after the emulation version and + // have higher priority than APIs of the same group resource enabled at the emulation version. + // If true, all APIs that have higher priority than the APIs(beta+) of the same group resource enabled at the emulation version will be installed. + // This is needed when a controller implementation migrates to newer API versions, for the binary version, and also uses the newer API versions even when emulation version is set. + // Not applicable to alpha APIs. + EmulationForwardCompatible bool + // RuntimeConfigEmulationForwardCompatible is an option to explicitly enable specific APIs introduced after the emulation version through the runtime-config. + // If true, APIs identified by group/version that are enabled in the --runtime-config flag will be installed even if it is introduced after the emulation version. --runtime-config flag values that identify multiple APIs, such as api/all,api/ga,api/beta, are not influenced by this flag and will only enable APIs available at the current emulation version. + // If false, error would be thrown if any GroupVersion or GroupVersionResource explicitly enabled in the --runtime-config flag is introduced after the emulation version. + RuntimeConfigEmulationForwardCompatible bool } func NewServerRunOptions() *ServerRunOptions { - if featuregate.DefaultComponentGlobalsRegistry.EffectiveVersionFor(featuregate.DefaultKubeComponent) == nil { + if compatibility.DefaultComponentGlobalsRegistry.EffectiveVersionFor(basecompatibility.DefaultKubeComponent) == nil { featureGate := utilfeature.DefaultMutableFeatureGate - effectiveVersion := utilversion.DefaultKubeEffectiveVersion() - utilruntime.Must(featuregate.DefaultComponentGlobalsRegistry.Register(featuregate.DefaultKubeComponent, effectiveVersion, featureGate)) + effectiveVersion := compatibility.DefaultBuildEffectiveVersion() + utilruntime.Must(compatibility.DefaultComponentGlobalsRegistry.Register(basecompatibility.DefaultKubeComponent, effectiveVersion, featureGate)) } - return NewServerRunOptionsForComponent(featuregate.DefaultKubeComponent, featuregate.DefaultComponentGlobalsRegistry) + return NewServerRunOptionsForComponent(basecompatibility.DefaultKubeComponent, compatibility.DefaultComponentGlobalsRegistry) } -func NewServerRunOptionsForComponent(componentName string, componentGlobalsRegistry featuregate.ComponentGlobalsRegistry) *ServerRunOptions { +func NewServerRunOptionsForComponent(componentName string, componentGlobalsRegistry basecompatibility.ComponentGlobalsRegistry) *ServerRunOptions { defaults := server.NewConfig(serializer.CodecFactory{}) return &ServerRunOptions{ MaxRequestsInFlight: defaults.MaxRequestsInFlight, @@ -152,6 +162,8 @@ func (s *ServerRunOptions) ApplyTo(c *server.Config) error { c.ShutdownWatchTerminationGracePeriod = s.ShutdownWatchTerminationGracePeriod c.EffectiveVersion = s.ComponentGlobalsRegistry.EffectiveVersionFor(s.ComponentName) c.FeatureGate = s.ComponentGlobalsRegistry.FeatureGateFor(s.ComponentName) + c.EmulationForwardCompatible = s.EmulationForwardCompatible + c.RuntimeConfigEmulationForwardCompatible = s.RuntimeConfigEmulationForwardCompatible return nil } @@ -231,6 +243,17 @@ func (s *ServerRunOptions) Validate() []error { if errs := s.ComponentGlobalsRegistry.Validate(); len(errs) != 0 { errors = append(errors, errs...) } + effectiveVersion := s.ComponentGlobalsRegistry.EffectiveVersionFor(s.ComponentName) + if effectiveVersion == nil { + return errors + } + notEmulationMode := effectiveVersion.BinaryVersion().WithPatch(0).EqualTo(effectiveVersion.EmulationVersion()) + if notEmulationMode && s.EmulationForwardCompatible { + errors = append(errors, fmt.Errorf("ServerRunOptions.EmulationForwardCompatible cannot be set to true if the emulation version is the same as the binary version")) + } + if notEmulationMode && s.RuntimeConfigEmulationForwardCompatible { + errors = append(errors, fmt.Errorf("ServerRunOptions.RuntimeConfigEmulationForwardCompatible cannot be set to true if the emulation version is the same as the binary version")) + } return errors } @@ -376,6 +399,13 @@ func (s *ServerRunOptions) AddUniversalFlags(fs *pflag.FlagSet) { "for active watch request(s) to drain during the graceful server shutdown window.") s.ComponentGlobalsRegistry.AddFlags(fs) + fs.BoolVar(&s.EmulationForwardCompatible, "emulation-forward-compatible", s.EmulationForwardCompatible, ""+ + "If true, for any beta+ APIs enabled by default or by --runtime-config at the emulation version, their future versions with higher priority/stability will be auto enabled even if they introduced after the emulation version. "+ + "Can only be set to true if the emulation version is lower than the binary version.") + fs.BoolVar(&s.RuntimeConfigEmulationForwardCompatible, "runtime-config-emulation-forward-compatible", s.RuntimeConfigEmulationForwardCompatible, ""+ + "If true, APIs identified by group/version that are enabled in the --runtime-config flag will be installed even if it is introduced after the emulation version. "+ + "If false, server would fail to start if any APIs identified by group/version that are enabled in the --runtime-config flag are introduced after the emulation version. "+ + "Can only be set to true if the emulation version is lower than the binary version.") } // Complete fills missing fields with defaults. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go b/e2e/vendor/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go index 2317be82d..980ddc61a 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go @@ -18,6 +18,7 @@ package options import ( "fmt" + "time" "github.com/google/uuid" @@ -49,9 +50,18 @@ func (s *SecureServingOptionsWithLoopback) ApplyTo(secureServingInfo **server.Se return nil } + // Set a validity period of approximately 3 years for the loopback certificate + // to avoid kube-apiserver disruptions due to certificate expiration. + // When this certificate expires, restarting kube-apiserver will automatically + // regenerate a new certificate with fresh validity dates. + maxAge := (3*365 + 1) * 24 * time.Hour + // create self-signed cert+key with the fake server.LoopbackClientServerNameOverride and // let the server return it when the loopback client connects. - certPem, keyPem, err := certutil.GenerateSelfSignedCertKey(server.LoopbackClientServerNameOverride, nil, nil) + certPem, keyPem, err := certutil.GenerateSelfSignedCertKeyWithOptions(certutil.SelfSignedCertKeyOptions{ + Host: server.LoopbackClientServerNameOverride, + MaxAge: maxAge, + }) if err != nil { return fmt.Errorf("failed to generate self-signed certificate for loopback connection: %v", err) } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/doc.go index 0dae21535..a6055414b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package resourceconfig contains the resource config related helper functions. -package resourceconfig // import "k8s.io/apiserver/pkg/server/resourceconfig" +package resourceconfig diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go b/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go index e90aa9161..c546112ec 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go @@ -19,11 +19,13 @@ package resourceconfig import ( "fmt" "regexp" + "sort" "strconv" "strings" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/version" serverstore "k8s.io/apiserver/pkg/server/storage" cliflag "k8s.io/component-base/cli/flag" ) @@ -36,6 +38,8 @@ type GroupVersionRegistry interface { IsVersionRegistered(v schema.GroupVersion) bool // PrioritizedVersionsAllGroups returns all registered group versions. PrioritizedVersionsAllGroups() []schema.GroupVersion + // PrioritizedVersionsForGroup returns versions for a single group in priority order + PrioritizedVersionsForGroup(group string) []schema.GroupVersion } // MergeResourceEncodingConfigs merges the given defaultResourceConfig with specific GroupVersionResource overrides. @@ -100,7 +104,17 @@ func MergeAPIResourceConfigs( } } } + if err := applyVersionAndResourcePreferences(resourceConfig, overrides, registry); err != nil { + return nil, err + } + return resourceConfig, nil +} +func applyVersionAndResourcePreferences( + resourceConfig *serverstore.ResourceConfig, + overrides cliflag.ConfigurationMap, + registry GroupVersionRegistry, +) error { type versionEnablementPreference struct { key string enabled bool @@ -130,7 +144,7 @@ func MergeAPIResourceConfigs( groupVersionString := tokens[0] + "/" + tokens[1] groupVersion, err := schema.ParseGroupVersion(groupVersionString) if err != nil { - return nil, fmt.Errorf("invalid key %s", key) + return fmt.Errorf("invalid key %s", key) } // Exclude group not registered into the registry. @@ -140,11 +154,11 @@ func MergeAPIResourceConfigs( // Verify that the groupVersion is registered into registry. if !registry.IsVersionRegistered(groupVersion) { - return nil, fmt.Errorf("group version %s that has not been registered", groupVersion.String()) + return fmt.Errorf("group version %s that has not been registered", groupVersion.String()) } enabled, err := getRuntimeConfigValue(overrides, key, false) if err != nil { - return nil, err + return err } switch len(tokens) { @@ -156,7 +170,7 @@ func MergeAPIResourceConfigs( }) case 3: if strings.ToLower(tokens[2]) != tokens[2] { - return nil, fmt.Errorf("invalid key %v: group/version/resource and resource is always lowercase plural, not %q", key, tokens[2]) + return fmt.Errorf("invalid key %v: group/version/resource and resource is always lowercase plural, not %q", key, tokens[2]) } resourcePreferences = append(resourcePreferences, resourceEnablementPreference{ key: key, @@ -170,11 +184,11 @@ func MergeAPIResourceConfigs( for _, versionPreference := range versionPreferences { if versionPreference.enabled { // enable the groupVersion for "group/version=true" - resourceConfig.EnableVersions(versionPreference.groupVersion) + resourceConfig.ExplicitlyEnableVersions(versionPreference.groupVersion) } else { // disable the groupVersion only for "group/version=false" - resourceConfig.DisableVersions(versionPreference.groupVersion) + resourceConfig.ExplicitlyDisableVersions(versionPreference.groupVersion) } } @@ -182,13 +196,12 @@ func MergeAPIResourceConfigs( for _, resourcePreference := range resourcePreferences { if resourcePreference.enabled { // enable the resource for "group/version/resource=true" - resourceConfig.EnableResources(resourcePreference.groupVersionResource) + resourceConfig.ExplicitlyEnableResources(resourcePreference.groupVersionResource) } else { - resourceConfig.DisableResources(resourcePreference.groupVersionResource) + resourceConfig.ExplicitlyDisableResources(resourcePreference.groupVersionResource) } } - - return resourceConfig, nil + return nil } func getRuntimeConfigValue(overrides cliflag.ConfigurationMap, apiKey string, defaultValue bool) (bool, error) { @@ -227,3 +240,61 @@ func ParseGroups(resourceConfig cliflag.ConfigurationMap) ([]string, error) { return groups, nil } + +// EmulationForwardCompatibleResourceConfig creates a new ResourceConfig that besides all the enabled resources in resourceConfig, +// enables all higher priority versions of enabled resources, excluding alpha versions. +// This is useful for ensuring forward compatibility when a new version of an API is introduced. +func EmulationForwardCompatibleResourceConfig( + resourceConfig *serverstore.ResourceConfig, + resourceConfigOverrides cliflag.ConfigurationMap, + registry GroupVersionRegistry, +) (*serverstore.ResourceConfig, error) { + ret := serverstore.NewResourceConfig() + for gv, enabled := range resourceConfig.GroupVersionConfigs { + ret.GroupVersionConfigs[gv] = enabled + if !enabled { + continue + } + // emulation forward compatibility is not applicable to alpha apis. + if alphaPattern.MatchString(gv.Version) { + continue + } + // if a gv is enabled, all the versions with higher priority (all the versions before gv in PrioritizedVersionsForGroup) are also implicitly enabled for emulation forward compatibility. + prioritizedVersions := registry.PrioritizedVersionsForGroup(gv.Group) + sort.Slice(prioritizedVersions, func(i, j int) bool { + return version.CompareKubeAwareVersionStrings(prioritizedVersions[i].Version, prioritizedVersions[j].Version) > 0 + }) + for _, pgv := range prioritizedVersions { + if pgv.Version == gv.Version { + break + } + ret.EnableVersions(pgv) + } + } + for gvr, enabled := range resourceConfig.ResourceConfigs { + ret.ResourceConfigs[gvr] = enabled + if !enabled { + continue + } + // emulation forward compatibility is not applicable to alpha apis. + if alphaPattern.MatchString(gvr.Version) { + continue + } + // if a gvr is enabled, all the versions with the same resource name and higher priority (all the versions before gv in PrioritizedVersionsForGroup) are also implicitly enabled for emulation forward compatibility. + prioritizedVersions := registry.PrioritizedVersionsForGroup(gvr.Group) + sort.Slice(prioritizedVersions, func(i, j int) bool { + return version.CompareKubeAwareVersionStrings(prioritizedVersions[i].Version, prioritizedVersions[j].Version) > 0 + }) + for _, pgv := range prioritizedVersions { + if pgv.Version == gvr.Version { + break + } + ret.EnableResources(pgv.WithResource(gvr.Resource)) + } + } + // need to reapply the version preferences if there is an override of a higher priority version. + if err := applyVersionAndResourcePreferences(ret, resourceConfigOverrides, registry); err != nil { + return nil, err + } + return ret, nil +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/routes/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/routes/doc.go index 603e899cd..adefbd3d5 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/routes/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/routes/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package routes holds a collection of optional genericapiserver http handlers. -package routes // import "k8s.io/apiserver/pkg/server/routes" +package routes diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/routes/version.go b/e2e/vendor/k8s.io/apiserver/pkg/server/routes/version.go index d2235f2ee..3e72f18ef 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/routes/version.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/routes/version.go @@ -39,10 +39,10 @@ func (v Version) Install(c *restful.Container) { // Set up a service to return the git code version. versionWS := new(restful.WebService) versionWS.Path("/version") - versionWS.Doc("git code version from which this is built") + versionWS.Doc("get the version information for this server.") versionWS.Route( versionWS.GET("/").To(v.handleVersion). - Doc("get the code version"). + Doc("get the version information for this server"). Operation("getCodeVersion"). Produces(restful.MIME_JSON). Consumes(restful.MIME_JSON). diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/secure_serving.go b/e2e/vendor/k8s.io/apiserver/pkg/server/secure_serving.go index 0a4fdc693..867c7efac 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/secure_serving.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/secure_serving.go @@ -172,33 +172,31 @@ func (s *SecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Dur ReadHeaderTimeout: 32 * time.Second, // just shy of requestTimeoutUpperBound } - // At least 99% of serialized resources in surveyed clusters were smaller than 256kb. - // This should be big enough to accommodate most API POST requests in a single frame, - // and small enough to allow a per connection buffer of this size multiplied by `MaxConcurrentStreams`. - const resourceBody99Percentile = 256 * 1024 - - http2Options := &http2.Server{ - IdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout - } - - // shrink the per-stream buffer and max framesize from the 1MB default while still accommodating most API POST requests in a single frame - http2Options.MaxUploadBufferPerStream = resourceBody99Percentile - http2Options.MaxReadFrameSize = resourceBody99Percentile - - // use the overridden concurrent streams setting or make the default of 250 explicit so we can size MaxUploadBufferPerConnection appropriately - if s.HTTP2MaxStreamsPerConnection > 0 { - http2Options.MaxConcurrentStreams = uint32(s.HTTP2MaxStreamsPerConnection) - } else { - // match http2.initialMaxConcurrentStreams used by clients - // this makes it so that a malicious client can only open 400 streams before we forcibly close the connection - // https://github.com/golang/net/commit/b225e7ca6dde1ef5a5ae5ce922861bda011cfabd - http2Options.MaxConcurrentStreams = 100 - } - - // increase the connection buffer size from the 1MB default to handle the specified number of concurrent streams - http2Options.MaxUploadBufferPerConnection = http2Options.MaxUploadBufferPerStream * int32(http2Options.MaxConcurrentStreams) - if !s.DisableHTTP2 { + // At least 99% of serialized resources in surveyed clusters were smaller than 256kb. + // This should be big enough to accommodate most API POST requests in a single frame, + // and small enough to allow a per connection buffer of this size multiplied by `MaxConcurrentStreams`. + const resourceBody99Percentile = 256 * 1024 + + http2Options := &http2.Server{ + IdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout + // shrink the per-stream buffer and max framesize from the 1MB default while still accommodating most API POST requests in a single frame + MaxUploadBufferPerStream: resourceBody99Percentile, + MaxReadFrameSize: resourceBody99Percentile, + } + + // use the overridden concurrent streams setting or make the default of 250 explicit so we can size MaxUploadBufferPerConnection appropriately + if s.HTTP2MaxStreamsPerConnection > 0 { + http2Options.MaxConcurrentStreams = uint32(s.HTTP2MaxStreamsPerConnection) + } else { + // match http2.initialMaxConcurrentStreams used by clients + // this makes it so that a malicious client can only open 400 streams before we forcibly close the connection + // https://github.com/golang/net/commit/b225e7ca6dde1ef5a5ae5ce922861bda011cfabd + http2Options.MaxConcurrentStreams = 100 + } + + // increase the connection buffer size from the 1MB default to handle the specified number of concurrent streams + http2Options.MaxUploadBufferPerConnection = http2Options.MaxUploadBufferPerStream * int32(http2Options.MaxConcurrentStreams) // apply settings to the server if err := http2.ConfigureServer(secureServer, http2Options); err != nil { return nil, nil, fmt.Errorf("error configuring http2: %v", err) @@ -236,8 +234,11 @@ func RunServer( defer close(serverShutdownCh) <-stopCh ctx, cancel := context.WithTimeout(context.Background(), shutDownTimeout) - server.Shutdown(ctx) - cancel() + defer cancel() + err := server.Shutdown(ctx) + if err != nil { + klog.Errorf("Failed to shutdown server: %v", err) + } }() go func() { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/doc.go index 36b0d2252..71d4e2be7 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package storage contains the plumbing to setup the etcd storage of the apiserver. -package storage // import "k8s.io/apiserver/pkg/server/storage" +package storage diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_config.go b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_config.go index ce8d1822a..b6b3bbae4 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_config.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_config.go @@ -24,17 +24,26 @@ import ( type APIResourceConfigSource interface { ResourceEnabled(resource schema.GroupVersionResource) bool AnyResourceForGroupEnabled(group string) bool + ResourceExplicitlyEnabled(resource schema.GroupVersionResource) bool + VersionExplicitlyEnabled(version schema.GroupVersion) bool } var _ APIResourceConfigSource = &ResourceConfig{} type ResourceConfig struct { - GroupVersionConfigs map[schema.GroupVersion]bool - ResourceConfigs map[schema.GroupVersionResource]bool + GroupVersionConfigs map[schema.GroupVersion]bool + ResourceConfigs map[schema.GroupVersionResource]bool + ExplicitGroupVersionConfigs map[schema.GroupVersion]bool + ExplicitResourceConfigs map[schema.GroupVersionResource]bool } func NewResourceConfig() *ResourceConfig { - return &ResourceConfig{GroupVersionConfigs: map[schema.GroupVersion]bool{}, ResourceConfigs: map[schema.GroupVersionResource]bool{}} + return &ResourceConfig{ + GroupVersionConfigs: map[schema.GroupVersion]bool{}, + ResourceConfigs: map[schema.GroupVersionResource]bool{}, + ExplicitGroupVersionConfigs: map[schema.GroupVersion]bool{}, + ExplicitResourceConfigs: map[schema.GroupVersionResource]bool{}, + } } // DisableMatchingVersions disables all group/versions for which the matcher function returns true. @@ -77,6 +86,7 @@ func (o *ResourceConfig) removeMatchingResourcePreferences(matcher func(gvr sche } for _, k := range keysToRemove { delete(o.ResourceConfigs, k) + delete(o.ExplicitResourceConfigs, k) } } @@ -91,6 +101,13 @@ func (o *ResourceConfig) DisableVersions(versions ...schema.GroupVersion) { } } +func (o *ResourceConfig) ExplicitlyDisableVersions(versions ...schema.GroupVersion) { + for _, version := range versions { + o.ExplicitGroupVersionConfigs[version] = false + } + o.DisableVersions(versions...) +} + // EnableVersions enables all resources in a given groupVersion. // This will remove any preferences previously set on individual resources. func (o *ResourceConfig) EnableVersions(versions ...schema.GroupVersion) { @@ -103,10 +120,16 @@ func (o *ResourceConfig) EnableVersions(versions ...schema.GroupVersion) { } +func (o *ResourceConfig) ExplicitlyEnableVersions(versions ...schema.GroupVersion) { + for _, version := range versions { + o.ExplicitGroupVersionConfigs[version] = true + } + o.EnableVersions(versions...) +} + // TODO this must be removed and we enable/disable individual resources. func (o *ResourceConfig) versionEnabled(version schema.GroupVersion) bool { - enabled, _ := o.GroupVersionConfigs[version] - return enabled + return o.GroupVersionConfigs[version] } func (o *ResourceConfig) DisableResources(resources ...schema.GroupVersionResource) { @@ -115,12 +138,26 @@ func (o *ResourceConfig) DisableResources(resources ...schema.GroupVersionResour } } +func (o *ResourceConfig) ExplicitlyDisableResources(resources ...schema.GroupVersionResource) { + for _, resource := range resources { + o.ExplicitResourceConfigs[resource] = false + } + o.DisableResources(resources...) +} + func (o *ResourceConfig) EnableResources(resources ...schema.GroupVersionResource) { for _, resource := range resources { o.ResourceConfigs[resource] = true } } +func (o *ResourceConfig) ExplicitlyEnableResources(resources ...schema.GroupVersionResource) { + for _, resource := range resources { + o.ExplicitResourceConfigs[resource] = true + } + o.EnableResources(resources...) +} + func (o *ResourceConfig) ResourceEnabled(resource schema.GroupVersionResource) bool { // if a resource is explicitly set, that takes priority over the preference of the version. resourceEnabled, explicitlySet := o.ResourceConfigs[resource] @@ -151,3 +188,19 @@ func (o *ResourceConfig) AnyResourceForGroupEnabled(group string) bool { return false } + +func (o *ResourceConfig) ResourceExplicitlyEnabled(resource schema.GroupVersionResource) bool { + resourceEnabled, explicitlySet := o.ExplicitResourceConfigs[resource] + if explicitlySet { + return resourceEnabled + } + return false +} + +func (o *ResourceConfig) VersionExplicitlyEnabled(version schema.GroupVersion) bool { + versionEnabled, explicitlySet := o.ExplicitGroupVersionConfigs[version] + if explicitlySet { + return versionEnabled + } + return false +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go index ce1bec676..612983cca 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go @@ -22,7 +22,8 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" apimachineryversion "k8s.io/apimachinery/pkg/util/version" - version "k8s.io/component-base/version" + "k8s.io/apiserver/pkg/util/compatibility" + basecompatibility "k8s.io/component-base/compatibility" ) type ResourceEncodingConfig interface { @@ -43,7 +44,7 @@ type DefaultResourceEncodingConfig struct { // resources records the overriding encoding configs for individual resources. resources map[schema.GroupResource]*OverridingResourceEncoding scheme *runtime.Scheme - effectiveVersion version.EffectiveVersion + effectiveVersion basecompatibility.EffectiveVersion } type OverridingResourceEncoding struct { @@ -54,7 +55,11 @@ type OverridingResourceEncoding struct { var _ ResourceEncodingConfig = &DefaultResourceEncodingConfig{} func NewDefaultResourceEncodingConfig(scheme *runtime.Scheme) *DefaultResourceEncodingConfig { - return &DefaultResourceEncodingConfig{resources: map[schema.GroupResource]*OverridingResourceEncoding{}, scheme: scheme, effectiveVersion: version.DefaultKubeEffectiveVersion()} + return NewDefaultResourceEncodingConfigForEffectiveVersion(scheme, compatibility.DefaultComponentGlobalsRegistry.EffectiveVersionFor(basecompatibility.DefaultKubeComponent)) +} + +func NewDefaultResourceEncodingConfigForEffectiveVersion(scheme *runtime.Scheme, effectiveVersion basecompatibility.EffectiveVersion) *DefaultResourceEncodingConfig { + return &DefaultResourceEncodingConfig{resources: map[schema.GroupResource]*OverridingResourceEncoding{}, scheme: scheme, effectiveVersion: effectiveVersion} } func (o *DefaultResourceEncodingConfig) SetResourceEncoding(resourceBeingStored schema.GroupResource, externalEncodingVersion, internalVersion schema.GroupVersion) { @@ -64,7 +69,7 @@ func (o *DefaultResourceEncodingConfig) SetResourceEncoding(resourceBeingStored } } -func (o *DefaultResourceEncodingConfig) SetEffectiveVersion(effectiveVersion version.EffectiveVersion) { +func (o *DefaultResourceEncodingConfig) SetEffectiveVersion(effectiveVersion basecompatibility.EffectiveVersion) { o.effectiveVersion = effectiveVersion } @@ -121,7 +126,7 @@ type replacementInterface interface { APILifecycleReplacement() schema.GroupVersionKind } -func emulatedStorageVersion(binaryVersionOfResource schema.GroupVersion, example runtime.Object, effectiveVersion version.EffectiveVersion, scheme *runtime.Scheme) (schema.GroupVersion, error) { +func emulatedStorageVersion(binaryVersionOfResource schema.GroupVersion, example runtime.Object, effectiveVersion basecompatibility.EffectiveVersion, scheme *runtime.Scheme) (schema.GroupVersion, error) { if example == nil || effectiveVersion == nil { return binaryVersionOfResource, nil } @@ -172,7 +177,7 @@ func emulatedStorageVersion(binaryVersionOfResource schema.GroupVersion, example } // If it was introduced after current compatibility version, don't use it - // skip the introduced check for test when currentVersion is 0.0 to test all apis + // skip the introduced check for test when current compatibility version is 0.0 to test all apis if introduced, hasIntroduced := exampleOfGVK.(introducedInterface); hasIntroduced && (compatibilityVersion.Major() > 0 || compatibilityVersion.Minor() > 0) { // Skip versions that have a replacement. diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/cacher.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/cacher.go index a5b5506dc..5d18d8313 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/cacher.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/cacher.go @@ -42,7 +42,9 @@ import ( "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/storage" + "k8s.io/apiserver/pkg/storage/cacher/delegator" "k8s.io/apiserver/pkg/storage/cacher/metrics" + "k8s.io/apiserver/pkg/storage/cacher/progress" etcdfeature "k8s.io/apiserver/pkg/storage/feature" utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/client-go/tools/cache" @@ -61,10 +63,16 @@ const ( // storageWatchListPageSize is the cacher's request chunk size of // initial and resync watch lists to storage. storageWatchListPageSize = int64(10000) + + // DefaultEventFreshDuration is the default time duration of events + // we want to keep. + // We set it to defaultBookmarkFrequency plus epsilon to maximize + // chances that last bookmark was sent within kept history, at the + // same time, minimizing the needed memory usage. + DefaultEventFreshDuration = defaultBookmarkFrequency + 15*time.Second + // defaultBookmarkFrequency defines how frequently watch bookmarks should be send // in addition to sending a bookmark right before watch deadline. - // - // NOTE: Update `eventFreshDuration` when changing this value. defaultBookmarkFrequency = time.Minute ) @@ -80,6 +88,10 @@ type Config struct { // and metrics. GroupResource schema.GroupResource + // EventsHistoryWindow specifies minimum history duration that storage is keeping. + // If lower than DefaultEventFreshDuration, the cache creation will fail. + EventsHistoryWindow time.Duration + // The Cache will be caching objects of a given Type and assumes that they // are all stored under ResourcePrefix directory in the underlying database. ResourcePrefix string @@ -329,10 +341,6 @@ type Cacher struct { expiredBookmarkWatchers []*cacheWatcher } -func (c *Cacher) RequestWatchProgress(ctx context.Context) error { - return c.storage.RequestWatchProgress(ctx) -} - // NewCacherFromConfig creates a new Cacher responsible for servicing WATCH and LIST requests from // its internal cache and updating its cache in the background based on the // given configuration. @@ -368,7 +376,7 @@ func NewCacherFromConfig(config Config) (*Cacher, error) { objType := reflect.TypeOf(obj) cacher := &Cacher{ resourcePrefix: config.ResourcePrefix, - ready: newReady(), + ready: newReady(config.Clock), storage: config.Storage, objectType: objType, groupResource: config.GroupResource, @@ -409,9 +417,15 @@ func NewCacherFromConfig(config Config) (*Cacher, error) { contextMetadata = metadata.New(map[string]string{"source": "cache"}) } - progressRequester := newConditionalProgressRequester(config.Storage.RequestWatchProgress, config.Clock, contextMetadata) + eventFreshDuration := config.EventsHistoryWindow + if eventFreshDuration < DefaultEventFreshDuration { + return nil, fmt.Errorf("config.EventsHistoryWindow (%v) must not be below %v", eventFreshDuration, DefaultEventFreshDuration) + } + + progressRequester := progress.NewConditionalProgressRequester(config.Storage.RequestWatchProgress, config.Clock, contextMetadata) watchCache := newWatchCache( - config.KeyFunc, cacher.processEvent, config.GetAttrsFunc, config.Versioner, config.Indexers, config.Clock, config.GroupResource, progressRequester) + config.KeyFunc, cacher.processEvent, config.GetAttrsFunc, config.Versioner, config.Indexers, + config.Clock, eventFreshDuration, config.GroupResource, progressRequester) listerWatcher := NewListerWatcher(config.Storage, config.ResourcePrefix, config.NewListFunc, contextMetadata) reflectorName := "storage/cacher.go:" + config.ResourcePrefix @@ -450,85 +464,30 @@ func NewCacherFromConfig(config Config) (*Cacher, error) { } func (c *Cacher) startCaching(stopChannel <-chan struct{}) { - // The 'usable' lock is always 'RLock'able when it is safe to use the cache. - // It is safe to use the cache after a successful list until a disconnection. - // We start with usable (write) locked. The below OnReplace function will - // unlock it after a successful list. The below defer will then re-lock - // it when this function exits (always due to disconnection), only if - // we actually got a successful list. This cycle will repeat as needed. - successfulList := false c.watchCache.SetOnReplace(func() { - successfulList = true - c.ready.set(true) + c.ready.setReady() klog.V(1).Infof("cacher (%v): initialized", c.groupResource.String()) metrics.WatchCacheInitializations.WithLabelValues(c.groupResource.String()).Inc() }) + var err error defer func() { - if successfulList { - c.ready.set(false) - } + c.ready.setError(err) }() c.terminateAllWatchers() - // Note that since onReplace may be not called due to errors, we explicitly - // need to retry it on errors under lock. - // Also note that startCaching is called in a loop, so there's no need - // to have another loop here. - if err := c.reflector.ListAndWatch(stopChannel); err != nil { + err = c.reflector.ListAndWatch(stopChannel) + if err != nil { klog.Errorf("cacher (%v): unexpected ListAndWatch error: %v; reinitializing...", c.groupResource.String(), err) } } -// Versioner implements storage.Interface. -func (c *Cacher) Versioner() storage.Versioner { - return c.storage.Versioner() -} - -// Create implements storage.Interface. -func (c *Cacher) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error { - return c.storage.Create(ctx, key, obj, out, ttl) -} - -// Delete implements storage.Interface. -func (c *Cacher) Delete( - ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions, - validateDeletion storage.ValidateObjectFunc, _ runtime.Object, opts storage.DeleteOptions) error { - // Ignore the suggestion and try to pass down the current version of the object - // read from cache. - if elem, exists, err := c.watchCache.GetByKey(key); err != nil { - klog.Errorf("GetByKey returned error: %v", err) - } else if exists { - // DeepCopy the object since we modify resource version when serializing the - // current object. - currObj := elem.(*storeElement).Object.DeepCopyObject() - return c.storage.Delete(ctx, key, out, preconditions, validateDeletion, currObj, opts) - } - // If we couldn't get the object, fallback to no-suggestion. - return c.storage.Delete(ctx, key, out, preconditions, validateDeletion, nil, opts) -} - type namespacedName struct { namespace string name string } -// Watch implements storage.Interface. func (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error) { pred := opts.Predicate - // if the watch-list feature wasn't set and the resourceVersion is unset - // ensure that the rv from which the watch is being served, is the latest - // one. "latest" is ensured by serving the watch from - // the underlying storage. - // - // it should never happen due to our validation but let's just be super-safe here - // and disable sendingInitialEvents when the feature wasn't enabled - if !utilfeature.DefaultFeatureGate.Enabled(features.WatchList) && opts.SendInitialEvents != nil { - opts.SendInitialEvents = nil - } - // TODO: we should eventually get rid of this legacy case - if utilfeature.DefaultFeatureGate.Enabled(features.WatchFromStorageWithoutResourceVersion) && opts.SendInitialEvents == nil && opts.ResourceVersion == "" { - return c.storage.Watch(ctx, key, opts) - } requestedWatchRV, err := c.versioner.ParseResourceVersion(opts.ResourceVersion) if err != nil { return nil, err @@ -536,10 +495,11 @@ func (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions var readyGeneration int if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { - var ok bool - readyGeneration, ok = c.ready.checkAndReadGeneration() - if !ok { - return nil, errors.NewTooManyRequests("storage is (re)initializing", 1) + var err error + var downtime time.Duration + readyGeneration, downtime, err = c.ready.checkAndReadGeneration() + if err != nil { + return nil, errors.NewTooManyRequests(err.Error(), calculateRetryAfterForUnreadyCache(downtime)) } } else { readyGeneration, err = c.ready.waitAndReadGeneration(ctx) @@ -660,7 +620,7 @@ func (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions c.Lock() defer c.Unlock() - if generation, ok := c.ready.checkAndReadGeneration(); generation != readyGeneration || !ok { + if generation, _, err := c.ready.checkAndReadGeneration(); generation != readyGeneration || err != nil { // We went unready or are already on a different generation. // Avoid registering and starting the watch as it will have to be // terminated immediately anyway. @@ -693,58 +653,17 @@ func (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions return watcher, nil } -// Get implements storage.Interface. func (c *Cacher) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error { - ctx, span := tracing.Start(ctx, "cacher.Get", - attribute.String("audit-id", audit.GetAuditIDTruncated(ctx)), - attribute.String("key", key), - attribute.String("resource-version", opts.ResourceVersion)) - defer span.End(500 * time.Millisecond) - if opts.ResourceVersion == "" { - // If resourceVersion is not specified, serve it from underlying - // storage (for backward compatibility). - span.AddEvent("About to Get from underlying storage") - return c.storage.Get(ctx, key, opts, objPtr) - } - - if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { - if !c.ready.check() { - // If Cache is not initialized, delegate Get requests to storage - // as described in https://kep.k8s.io/4568 - span.AddEvent("About to Get from underlying storage - cache not initialized") - return c.storage.Get(ctx, key, opts, objPtr) - } - } - - // If resourceVersion is specified, serve it from cache. - // It's guaranteed that the returned value is at least that - // fresh as the given resourceVersion. getRV, err := c.versioner.ParseResourceVersion(opts.ResourceVersion) if err != nil { return err } - // Do not create a trace - it's not for free and there are tons - // of Get requests. We can add it if it will be really needed. - - if !utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { - if getRV == 0 && !c.ready.check() { - // If Cacher is not yet initialized and we don't require any specific - // minimal resource version, simply forward the request to storage. - span.AddEvent("About to Get from underlying storage - cache not initialized and no resourceVersion set") - return c.storage.Get(ctx, key, opts, objPtr) - } - if err := c.ready.wait(ctx); err != nil { - return errors.NewServiceUnavailable(err.Error()) - } - } - objVal, err := conversion.EnforcePtr(objPtr) if err != nil { return err } - span.AddEvent("About to fetch object from cache") obj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(ctx, getRV, key) if err != nil { return err @@ -765,28 +684,6 @@ func (c *Cacher) Get(ctx context.Context, key string, opts storage.GetOptions, o return nil } -// NOTICE: Keep in sync with shouldListFromStorage function in -// -// staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go -func shouldDelegateList(opts storage.ListOptions) bool { - resourceVersion := opts.ResourceVersion - pred := opts.Predicate - match := opts.ResourceVersionMatch - consistentListFromCacheEnabled := utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) - requestWatchProgressSupported := etcdfeature.DefaultFeatureSupportChecker.Supports(storage.RequestWatchProgress) - - // Serve consistent reads from storage if ConsistentListFromCache is disabled - consistentReadFromStorage := resourceVersion == "" && !(consistentListFromCacheEnabled && requestWatchProgressSupported) - // Watch cache doesn't support continuations, so serve them from etcd. - hasContinuation := len(pred.Continue) > 0 - // Watch cache only supports ResourceVersionMatchNotOlderThan (default). - // see https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list - isLegacyExactMatch := opts.Predicate.Limit > 0 && match == "" && len(resourceVersion) > 0 && resourceVersion != "0" - unsupportedMatch := match != "" && match != metav1.ResourceVersionMatchNotOlderThan || isLegacyExactMatch - - return consistentReadFromStorage || hasContinuation || unsupportedMatch -} - // computeListLimit determines whether the cacher should // apply a limit to an incoming LIST request and returns its value. // @@ -801,55 +698,27 @@ func computeListLimit(opts storage.ListOptions) int64 { return opts.Predicate.Limit } -func shouldDelegateListOnNotReadyCache(opts storage.ListOptions) bool { - pred := opts.Predicate - noLabelSelector := pred.Label == nil || pred.Label.Empty() - noFieldSelector := pred.Field == nil || pred.Field.Empty() - hasLimit := pred.Limit > 0 - return noLabelSelector && noFieldSelector && hasLimit -} - -func (c *Cacher) listItems(ctx context.Context, listRV uint64, key string, pred storage.SelectionPredicate, recursive bool) ([]interface{}, uint64, string, error) { - if !recursive { +func (c *Cacher) listItems(ctx context.Context, listRV uint64, key string, opts storage.ListOptions) (listResp, string, error) { + if !opts.Recursive { obj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(ctx, listRV, key) if err != nil { - return nil, 0, "", err + return listResp{}, "", err } if exists { - return []interface{}{obj}, readResourceVersion, "", nil + return listResp{Items: []interface{}{obj}, ResourceVersion: readResourceVersion}, "", nil } - return nil, readResourceVersion, "", nil + return listResp{ResourceVersion: readResourceVersion}, "", nil } - return c.watchCache.WaitUntilFreshAndList(ctx, listRV, key, pred.MatcherIndex(ctx)) + return c.watchCache.WaitUntilFreshAndList(ctx, listRV, key, opts) +} + +type listResp struct { + Items []interface{} + ResourceVersion uint64 } // GetList implements storage.Interface func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error { - recursive := opts.Recursive - resourceVersion := opts.ResourceVersion - pred := opts.Predicate - if shouldDelegateList(opts) { - return c.storage.GetList(ctx, key, opts, listObj) - } - - listRV, err := c.versioner.ParseResourceVersion(resourceVersion) - if err != nil { - return err - } - - if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { - if !c.ready.check() && shouldDelegateListOnNotReadyCache(opts) { - // If Cacher is not initialized, delegate List requests to storage - // as described in https://kep.k8s.io/4568 - return c.storage.GetList(ctx, key, opts, listObj) - } - } else { - if listRV == 0 && !c.ready.check() { - // If Cacher is not yet initialized and we don't require any specific - // minimal resource version, simply forward the request to storage. - return c.storage.GetList(ctx, key, opts, listObj) - } - } // For recursive lists, we need to make sure the key ended with "/" so that we only // get children "directories". e.g. if we have key "/a", "/a/b", "/ab", getting keys // with prefix "/a" will return all three, while with prefix "/a/" will return only @@ -858,13 +727,9 @@ func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptio if opts.Recursive && !strings.HasSuffix(key, "/") { preparedKey += "/" } - requestWatchProgressSupported := etcdfeature.DefaultFeatureSupportChecker.Supports(storage.RequestWatchProgress) - consistentRead := resourceVersion == "" && utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) && requestWatchProgressSupported - if consistentRead { - listRV, err = storage.GetCurrentResourceVersionFromStorage(ctx, c.storage, c.newListFunc, c.resourcePrefix, c.objectType.String()) - if err != nil { - return err - } + listRV, err := c.versioner.ParseResourceVersion(opts.ResourceVersion) + if err != nil { + return err } ctx, span := tracing.Start(ctx, "cacher.GetList", @@ -873,10 +738,10 @@ func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptio defer span.End(500 * time.Millisecond) if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { - if !c.ready.check() { + if downtime, err := c.ready.check(); err != nil { // If Cacher is not initialized, reject List requests // as described in https://kep.k8s.io/4568 - return errors.NewTooManyRequests("storage is (re)initializing", 1) + return errors.NewTooManyRequests(err.Error(), calculateRetryAfterForUnreadyCache(downtime)) } } else { if err := c.ready.wait(ctx); err != nil { @@ -898,26 +763,11 @@ func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptio return fmt.Errorf("need a pointer to slice, got %v", listVal.Kind()) } - objs, readResourceVersion, indexUsed, err := c.listItems(ctx, listRV, preparedKey, pred, recursive) - success := "true" - fallback := "false" + resp, indexUsed, err := c.listItems(ctx, listRV, preparedKey, opts) if err != nil { - if consistentRead { - if storage.IsTooLargeResourceVersion(err) { - fallback = "true" - err = c.storage.GetList(ctx, key, opts, listObj) - } - if err != nil { - success = "false" - } - metrics.ConsistentReadTotal.WithLabelValues(c.resourcePrefix, success, fallback).Add(1) - } return err } - if consistentRead { - metrics.ConsistentReadTotal.WithLabelValues(c.resourcePrefix, success, fallback).Add(1) - } - span.AddEvent("Listed items from cache", attribute.Int("count", len(objs))) + span.AddEvent("Listed items from cache", attribute.Int("count", len(resp.Items))) // store pointer of eligible objects, // Why not directly put object in the items of listObj? // the elements in ListObject are Struct type, making slice will bring excessive memory consumption. @@ -926,17 +776,17 @@ func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptio var lastSelectedObjectKey string var hasMoreListItems bool limit := computeListLimit(opts) - for i, obj := range objs { + for i, obj := range resp.Items { elem, ok := obj.(*storeElement) if !ok { return fmt.Errorf("non *storeElement returned from storage: %v", obj) } - if pred.MatchesObjectAttributes(elem.Labels, elem.Fields) { + if opts.Predicate.MatchesObjectAttributes(elem.Labels, elem.Fields) { selectedObjects = append(selectedObjects, elem.Object) lastSelectedObjectKey = elem.Key } if limit > 0 && int64(len(selectedObjects)) >= limit { - hasMoreListItems = i < len(objs)-1 + hasMoreListItems = i < len(resp.Items)-1 break } } @@ -953,47 +803,16 @@ func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptio } span.AddEvent("Filtered items", attribute.Int("count", listVal.Len())) if c.versioner != nil { - continueValue, remainingItemCount, err := storage.PrepareContinueToken(lastSelectedObjectKey, key, int64(readResourceVersion), int64(len(objs)), hasMoreListItems, opts) + continueValue, remainingItemCount, err := storage.PrepareContinueToken(lastSelectedObjectKey, key, int64(resp.ResourceVersion), int64(len(resp.Items)), hasMoreListItems, opts) if err != nil { return err } - if err = c.versioner.UpdateList(listObj, readResourceVersion, continueValue, remainingItemCount); err != nil { + if err = c.versioner.UpdateList(listObj, resp.ResourceVersion, continueValue, remainingItemCount); err != nil { return err } } - metrics.RecordListCacheMetrics(c.resourcePrefix, indexUsed, len(objs), listVal.Len()) - return nil -} - -// GuaranteedUpdate implements storage.Interface. -func (c *Cacher) GuaranteedUpdate( - ctx context.Context, key string, destination runtime.Object, ignoreNotFound bool, - preconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, _ runtime.Object) error { - // Ignore the suggestion and try to pass down the current version of the object - // read from cache. - if elem, exists, err := c.watchCache.GetByKey(key); err != nil { - klog.Errorf("GetByKey returned error: %v", err) - } else if exists { - // DeepCopy the object since we modify resource version when serializing the - // current object. - currObj := elem.(*storeElement).Object.DeepCopyObject() - return c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, currObj) - } - // If we couldn't get the object, fallback to no-suggestion. - return c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, nil) -} - -// Count implements storage.Interface. -func (c *Cacher) Count(pathPrefix string) (int64, error) { - return c.storage.Count(pathPrefix) -} - -// ReadinessCheck implements storage.Interface. -func (c *Cacher) ReadinessCheck() error { - if !c.ready.check() { - return storage.ErrStorageNotReady - } + metrics.RecordListCacheMetrics(c.resourcePrefix, indexUsed, len(resp.Items), listVal.Len()) return nil } @@ -1420,7 +1239,7 @@ func (c *Cacher) getWatchCacheResourceVersion(ctx context.Context, parsedWatchRe if !utilfeature.DefaultFeatureGate.Enabled(features.WatchFromStorageWithoutResourceVersion) && opts.SendInitialEvents == nil && opts.ResourceVersion == "" { return 0, nil } - rv, err := storage.GetCurrentResourceVersionFromStorage(ctx, c.storage, c.newListFunc, c.resourcePrefix, c.objectType.String()) + rv, err := c.storage.GetCurrentResourceVersion(ctx) return rv, err } @@ -1473,6 +1292,11 @@ func (c *Cacher) setInitialEventsEndBookmarkIfRequested(cacheInterval *watchCach } } +func (c *Cacher) Ready() bool { + _, err := c.ready.check() + return err == nil +} + // errWatcher implements watch.Interface to return a single error type errWatcher struct { result chan watch.Event @@ -1503,6 +1327,55 @@ func newErrWatcher(err error) *errWatcher { return watcher } +func (c *Cacher) ShouldDelegateExactRV(resourceVersion string, recursive bool) (delegator.Result, error) { + // Not Recursive is not supported unitl exact RV is implemented for WaitUntilFreshAndGet. + if !recursive || c.watchCache.snapshots == nil { + return delegator.Result{ShouldDelegate: true}, nil + } + listRV, err := c.versioner.ParseResourceVersion(resourceVersion) + if err != nil { + return delegator.Result{}, err + } + return c.shouldDelegateExactRV(listRV) +} + +func (c *Cacher) ShouldDelegateContinue(continueToken string, recursive bool) (delegator.Result, error) { + // Not Recursive is not supported unitl exact RV is implemented for WaitUntilFreshAndGet. + if !recursive || c.watchCache.snapshots == nil { + return delegator.Result{ShouldDelegate: true}, nil + } + _, continueRV, err := storage.DecodeContinue(continueToken, c.resourcePrefix) + if err != nil { + return delegator.Result{}, err + } + if continueRV > 0 { + return c.shouldDelegateExactRV(uint64(continueRV)) + } else { + // Continue with negative RV is a consistent read. + return c.ShouldDelegateConsistentRead() + } +} + +func (c *Cacher) shouldDelegateExactRV(rv uint64) (delegator.Result, error) { + // Exact requests on future revision require support for consistent read, but are not a consistent read by themselves. + if c.watchCache.notFresh(rv) { + return delegator.Result{ + ShouldDelegate: !delegator.ConsistentReadSupported(), + }, nil + } + _, canServe := c.watchCache.snapshots.GetLessOrEqual(rv) + return delegator.Result{ + ShouldDelegate: !canServe, + }, nil +} + +func (c *Cacher) ShouldDelegateConsistentRead() (delegator.Result, error) { + return delegator.Result{ + ConsistentRead: true, + ShouldDelegate: !delegator.ConsistentReadSupported(), + }, nil +} + // Implements watch.Interface. func (c *errWatcher) ResultChan() <-chan watch.Event { return c.result diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator.go new file mode 100644 index 000000000..ac17fb1c8 --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator.go @@ -0,0 +1,437 @@ +/* +Copyright 2015 The Kubernetes 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 cacher + +import ( + "context" + "fmt" + "hash" + "hash/fnv" + "os" + "strconv" + "sync" + "time" + + "go.opentelemetry.io/otel/attribute" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/apiserver/pkg/audit" + "k8s.io/apiserver/pkg/features" + "k8s.io/apiserver/pkg/storage" + "k8s.io/apiserver/pkg/storage/cacher/delegator" + "k8s.io/apiserver/pkg/storage/cacher/metrics" + utilfeature "k8s.io/apiserver/pkg/util/feature" + "k8s.io/component-base/tracing" + "k8s.io/klog/v2" +) + +var ( + // ConsistencyCheckPeriod is the period of checking consistency between etcd and cache. + // 5 minutes were proposed to match the default compaction period. It's magnitute higher than + // List latency SLO (30 seconds) and timeout (1 minute). + ConsistencyCheckPeriod = 5 * time.Minute + // ConsistencyCheckerEnabled enables the consistency checking mechanism for cache. + // Based on KUBE_WATCHCACHE_CONSISTENCY_CHECKER environment variable. + ConsistencyCheckerEnabled = false +) + +func init() { + ConsistencyCheckerEnabled, _ = strconv.ParseBool(os.Getenv("KUBE_WATCHCACHE_CONSISTENCY_CHECKER")) +} + +func NewCacheDelegator(cacher *Cacher, storage storage.Interface) *CacheDelegator { + d := &CacheDelegator{ + cacher: cacher, + storage: storage, + stopCh: make(chan struct{}), + } + if ConsistencyCheckerEnabled { + d.checker = newConsistencyChecker(cacher.resourcePrefix, cacher.newListFunc, cacher, storage) + d.wg.Add(1) + go func() { + defer d.wg.Done() + d.checker.startChecking(d.stopCh) + }() + } + return d +} + +type CacheDelegator struct { + cacher *Cacher + storage storage.Interface + checker *consistencyChecker + + wg sync.WaitGroup + stopOnce sync.Once + stopCh chan struct{} +} + +var _ storage.Interface = (*CacheDelegator)(nil) + +func (c *CacheDelegator) Versioner() storage.Versioner { + return c.storage.Versioner() +} + +func (c *CacheDelegator) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error { + return c.storage.Create(ctx, key, obj, out, ttl) +} + +func (c *CacheDelegator) GetCurrentResourceVersion(ctx context.Context) (uint64, error) { + return c.storage.GetCurrentResourceVersion(ctx) +} + +func (c *CacheDelegator) Delete(ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions, validateDeletion storage.ValidateObjectFunc, cachedExistingObject runtime.Object, opts storage.DeleteOptions) error { + // Ignore the suggestion and try to pass down the current version of the object + // read from cache. + if elem, exists, err := c.cacher.watchCache.GetByKey(key); err != nil { + klog.Errorf("GetByKey returned error: %v", err) + } else if exists { + // DeepCopy the object since we modify resource version when serializing the + // current object. + currObj := elem.(*storeElement).Object.DeepCopyObject() + return c.storage.Delete(ctx, key, out, preconditions, validateDeletion, currObj, opts) + } + // If we couldn't get the object, fallback to no-suggestion. + return c.storage.Delete(ctx, key, out, preconditions, validateDeletion, nil, opts) +} + +func (c *CacheDelegator) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error) { + // if the watch-list feature wasn't set and the resourceVersion is unset + // ensure that the rv from which the watch is being served, is the latest + // one. "latest" is ensured by serving the watch from + // the underlying storage. + // + // it should never happen due to our validation but let's just be super-safe here + // and disable sendingInitialEvents when the feature wasn't enabled + if !utilfeature.DefaultFeatureGate.Enabled(features.WatchList) && opts.SendInitialEvents != nil { + opts.SendInitialEvents = nil + } + // TODO: we should eventually get rid of this legacy case + if utilfeature.DefaultFeatureGate.Enabled(features.WatchFromStorageWithoutResourceVersion) && opts.SendInitialEvents == nil && opts.ResourceVersion == "" { + return c.storage.Watch(ctx, key, opts) + } + return c.cacher.Watch(ctx, key, opts) +} + +func (c *CacheDelegator) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error { + ctx, span := tracing.Start(ctx, "cacher.Get", + attribute.String("audit-id", audit.GetAuditIDTruncated(ctx)), + attribute.String("key", key), + attribute.String("resource-version", opts.ResourceVersion)) + defer span.End(500 * time.Millisecond) + if opts.ResourceVersion == "" { + // If resourceVersion is not specified, serve it from underlying + // storage (for backward compatibility). + span.AddEvent("About to Get from underlying storage") + return c.storage.Get(ctx, key, opts, objPtr) + } + + if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { + if !c.cacher.Ready() { + // If Cache is not initialized, delegator Get requests to storage + // as described in https://kep.k8s.io/4568 + span.AddEvent("About to Get from underlying storage - cache not initialized") + return c.storage.Get(ctx, key, opts, objPtr) + } + } + // If resourceVersion is specified, serve it from cache. + // It's guaranteed that the returned value is at least that + // fresh as the given resourceVersion. + getRV, err := c.cacher.versioner.ParseResourceVersion(opts.ResourceVersion) + if err != nil { + return err + } + // Do not create a trace - it's not for free and there are tons + // of Get requests. We can add it if it will be really needed. + if !utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { + if getRV == 0 && !c.cacher.Ready() { + // If Cacher is not yet initialized and we don't require any specific + // minimal resource version, simply forward the request to storage. + return c.storage.Get(ctx, key, opts, objPtr) + } + if err := c.cacher.ready.wait(ctx); err != nil { + return errors.NewServiceUnavailable(err.Error()) + } + } + span.AddEvent("About to fetch object from cache") + return c.cacher.Get(ctx, key, opts, objPtr) +} + +func (c *CacheDelegator) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error { + _, _, err := storage.ValidateListOptions(c.cacher.resourcePrefix, c.cacher.versioner, opts) + if err != nil { + return err + } + result, err := delegator.ShouldDelegateList(opts, c.cacher) + if err != nil { + return err + } + if result.ShouldDelegate { + return c.storage.GetList(ctx, key, opts, listObj) + } + + listRV, err := c.cacher.versioner.ParseResourceVersion(opts.ResourceVersion) + if err != nil { + return err + } + + if utilfeature.DefaultFeatureGate.Enabled(features.ResilientWatchCacheInitialization) { + if !c.cacher.Ready() && shouldDelegateListOnNotReadyCache(opts) { + // If Cacher is not initialized, delegator List requests to storage + // as described in https://kep.k8s.io/4568 + return c.storage.GetList(ctx, key, opts, listObj) + } + } else { + if listRV == 0 && !c.cacher.Ready() { + // If Cacher is not yet initialized and we don't require any specific + // minimal resource version, simply forward the request to storage. + return c.storage.GetList(ctx, key, opts, listObj) + } + } + if result.ConsistentRead { + listRV, err = c.storage.GetCurrentResourceVersion(ctx) + if err != nil { + return err + } + // Setting resource version for consistent read in cache based on current ResourceVersion in etcd. + opts.ResourceVersion = strconv.FormatInt(int64(listRV), 10) + } + err = c.cacher.GetList(ctx, key, opts, listObj) + success := "true" + fallback := "false" + if err != nil { + if errors.IsResourceExpired(err) { + return c.storage.GetList(ctx, key, opts, listObj) + } + if result.ConsistentRead { + if storage.IsTooLargeResourceVersion(err) { + fallback = "true" + // Reset resourceVersion during fallback from consistent read. + opts.ResourceVersion = "" + err = c.storage.GetList(ctx, key, opts, listObj) + } + if err != nil { + success = "false" + } + metrics.ConsistentReadTotal.WithLabelValues(c.cacher.resourcePrefix, success, fallback).Add(1) + } + return err + } + if result.ConsistentRead { + metrics.ConsistentReadTotal.WithLabelValues(c.cacher.resourcePrefix, success, fallback).Add(1) + } + return nil +} + +func shouldDelegateListOnNotReadyCache(opts storage.ListOptions) bool { + pred := opts.Predicate + noLabelSelector := pred.Label == nil || pred.Label.Empty() + noFieldSelector := pred.Field == nil || pred.Field.Empty() + hasLimit := pred.Limit > 0 + return noLabelSelector && noFieldSelector && hasLimit +} + +func (c *CacheDelegator) GuaranteedUpdate(ctx context.Context, key string, destination runtime.Object, ignoreNotFound bool, preconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, cachedExistingObject runtime.Object) error { + // Ignore the suggestion and try to pass down the current version of the object + // read from cache. + if elem, exists, err := c.cacher.watchCache.GetByKey(key); err != nil { + klog.Errorf("GetByKey returned error: %v", err) + } else if exists { + // DeepCopy the object since we modify resource version when serializing the + // current object. + currObj := elem.(*storeElement).Object.DeepCopyObject() + return c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, currObj) + } + // If we couldn't get the object, fallback to no-suggestion. + return c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, nil) +} + +func (c *CacheDelegator) Count(pathPrefix string) (int64, error) { + return c.storage.Count(pathPrefix) +} + +func (c *CacheDelegator) ReadinessCheck() error { + if !c.cacher.Ready() { + return storage.ErrStorageNotReady + } + return nil +} + +func (c *CacheDelegator) RequestWatchProgress(ctx context.Context) error { + return c.storage.RequestWatchProgress(ctx) +} + +func (c *CacheDelegator) Stop() { + c.stopOnce.Do(func() { + close(c.stopCh) + }) + c.wg.Wait() +} + +func newConsistencyChecker(resourcePrefix string, newListFunc func() runtime.Object, cacher getListerReady, etcd getLister) *consistencyChecker { + return &consistencyChecker{ + resourcePrefix: resourcePrefix, + newListFunc: newListFunc, + cacher: cacher, + etcd: etcd, + } +} + +type consistencyChecker struct { + resourcePrefix string + newListFunc func() runtime.Object + + cacher getListerReady + etcd getLister +} + +type getListerReady interface { + getLister + Ready() bool +} + +type getLister interface { + GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error +} + +func (c consistencyChecker) startChecking(stopCh <-chan struct{}) { + err := wait.PollUntilContextCancel(wait.ContextForChannel(stopCh), ConsistencyCheckPeriod, false, func(ctx context.Context) (done bool, err error) { + c.check(ctx) + return false, nil + }) + if err != nil { + klog.InfoS("Cache consistency check exiting", "resource", c.resourcePrefix, "err", err) + } +} + +func (c *consistencyChecker) check(ctx context.Context) { + digests, err := c.calculateDigests(ctx) + if err != nil { + klog.ErrorS(err, "Cache consistency check error", "resource", c.resourcePrefix) + metrics.StorageConsistencyCheckTotal.WithLabelValues(c.resourcePrefix, "error").Inc() + return + } + if digests.CacheDigest == digests.EtcdDigest { + klog.V(3).InfoS("Cache consistency check passed", "resource", c.resourcePrefix, "resourceVersion", digests.ResourceVersion, "digest", digests.CacheDigest) + metrics.StorageConsistencyCheckTotal.WithLabelValues(c.resourcePrefix, "success").Inc() + } else { + klog.ErrorS(nil, "Cache consistency check failed", "resource", c.resourcePrefix, "resourceVersion", digests.ResourceVersion, "etcdDigest", digests.EtcdDigest, "cacheDigest", digests.CacheDigest) + metrics.StorageConsistencyCheckTotal.WithLabelValues(c.resourcePrefix, "failure").Inc() + // Panic on internal consistency checking enabled only by environment variable. R + panic(fmt.Sprintf("Cache consistency check failed, resource: %q, resourceVersion: %q, etcdDigest: %q, cacheDigest: %q", c.resourcePrefix, digests.ResourceVersion, digests.EtcdDigest, digests.CacheDigest)) + } +} + +func (c *consistencyChecker) calculateDigests(ctx context.Context) (*storageDigest, error) { + if !c.cacher.Ready() { + return nil, fmt.Errorf("cache is not ready") + } + cacheDigest, resourceVersion, err := c.calculateStoreDigest(ctx, c.cacher, storage.ListOptions{ + Recursive: true, + ResourceVersion: "0", + Predicate: storage.Everything, + ResourceVersionMatch: metav1.ResourceVersionMatchNotOlderThan, + }) + if err != nil { + return nil, fmt.Errorf("failed calculating cache digest: %w", err) + } + etcdDigest, _, err := c.calculateStoreDigest(ctx, c.etcd, storage.ListOptions{ + Recursive: true, + ResourceVersion: resourceVersion, + Predicate: storage.Everything, + ResourceVersionMatch: metav1.ResourceVersionMatchExact, + }) + if err != nil { + return nil, fmt.Errorf("failed calculating etcd digest: %w", err) + } + return &storageDigest{ + ResourceVersion: resourceVersion, + CacheDigest: cacheDigest, + EtcdDigest: etcdDigest, + }, nil +} + +type storageDigest struct { + ResourceVersion string + CacheDigest string + EtcdDigest string +} + +func (c *consistencyChecker) calculateStoreDigest(ctx context.Context, store getLister, opts storage.ListOptions) (digest, rv string, err error) { + // TODO: Implement pagination + resp := c.newListFunc() + err = store.GetList(ctx, c.resourcePrefix, opts, resp) + if err != nil { + return "", "", err + } + digest, err = listDigest(resp) + if err != nil { + return "", "", err + } + list, err := meta.ListAccessor(resp) + if err != nil { + return "", "", err + } + return digest, list.GetResourceVersion(), nil +} + +func listDigest(list runtime.Object) (string, error) { + h := fnv.New64() + err := meta.EachListItem(list, func(obj runtime.Object) error { + objectMeta, err := meta.Accessor(obj) + if err != nil { + return err + } + err = addObjectToDigest(h, objectMeta) + if err != nil { + return err + } + return nil + }) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", h.Sum64()), nil +} + +func addObjectToDigest(h hash.Hash64, objectMeta metav1.Object) error { + _, err := h.Write([]byte(objectMeta.GetNamespace())) + if err != nil { + return err + } + _, err = h.Write([]byte("/")) + if err != nil { + return err + } + _, err = h.Write([]byte(objectMeta.GetName())) + if err != nil { + return err + } + _, err = h.Write([]byte("/")) + if err != nil { + return err + } + _, err = h.Write([]byte(objectMeta.GetResourceVersion())) + if err != nil { + return err + } + return nil +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator/interface.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator/interface.go new file mode 100644 index 000000000..1cdf5145e --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/delegator/interface.go @@ -0,0 +1,113 @@ +/* +Copyright 2025 The Kubernetes 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 delegator + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apiserver/pkg/features" + "k8s.io/apiserver/pkg/storage" + etcdfeature "k8s.io/apiserver/pkg/storage/feature" + utilfeature "k8s.io/apiserver/pkg/util/feature" +) + +func ShouldDelegateListMeta(opts *metav1.ListOptions, cache Helper) (Result, error) { + return ShouldDelegateList( + storage.ListOptions{ + ResourceVersionMatch: opts.ResourceVersionMatch, + ResourceVersion: opts.ResourceVersion, + Predicate: storage.SelectionPredicate{ + Continue: opts.Continue, + Limit: opts.Limit, + }, + Recursive: true, + }, cache) +} + +func ShouldDelegateList(opts storage.ListOptions, cache Helper) (Result, error) { + // see https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list + switch opts.ResourceVersionMatch { + case metav1.ResourceVersionMatchExact: + return cache.ShouldDelegateExactRV(opts.ResourceVersion, opts.Recursive) + case metav1.ResourceVersionMatchNotOlderThan: + return Result{ShouldDelegate: false}, nil + case "": + // Continue + if len(opts.Predicate.Continue) > 0 { + return cache.ShouldDelegateContinue(opts.Predicate.Continue, opts.Recursive) + } + // Legacy exact match + if opts.Predicate.Limit > 0 && len(opts.ResourceVersion) > 0 && opts.ResourceVersion != "0" { + return cache.ShouldDelegateExactRV(opts.ResourceVersion, opts.Recursive) + } + // Consistent Read + if opts.ResourceVersion == "" { + return cache.ShouldDelegateConsistentRead() + } + return Result{ShouldDelegate: false}, nil + default: + return Result{ShouldDelegate: true}, nil + } +} + +type Helper interface { + ShouldDelegateExactRV(rv string, recursive bool) (Result, error) + ShouldDelegateContinue(continueToken string, recursive bool) (Result, error) + ShouldDelegateConsistentRead() (Result, error) +} + +// Result of delegator decision. +type Result struct { + // Whether a request cannot be served by cache and should be delegated to etcd. + ShouldDelegate bool + // Whether a request is a consistent read, used by delegator to decide if it should call GetCurrentResourceVersion to get RV. + // Included in interface as only cacher has keyPrefix needed to parse continue token. + ConsistentRead bool +} + +type CacheWithoutSnapshots struct{} + +var _ Helper = CacheWithoutSnapshots{} + +func (c CacheWithoutSnapshots) ShouldDelegateContinue(continueToken string, recursive bool) (Result, error) { + return Result{ + ShouldDelegate: true, + // Continue with negative RV is considered a consistent read, however token cannot be parsed without keyPrefix unavailable in staging/src/k8s.io/apiserver/pkg/util/flow_control/request/list_work_estimator.go. + ConsistentRead: false, + }, nil +} + +func (c CacheWithoutSnapshots) ShouldDelegateExactRV(rv string, recursive bool) (Result, error) { + return Result{ + ShouldDelegate: true, + ConsistentRead: false, + }, nil +} + +func (c CacheWithoutSnapshots) ShouldDelegateConsistentRead() (Result, error) { + return Result{ + ShouldDelegate: !ConsistentReadSupported(), + ConsistentRead: true, + }, nil +} + +// ConsistentReadSupported returns whether cache can be used to serve reads with RV not yet observed by cache, including both consistent reads. +// Function is located here to avoid import cycles between staging/src/k8s.io/apiserver/pkg/storage/cacher/delegator.go and staging/src/k8s.io/apiserver/pkg/util/flow_control/request/list_work_estimator.go. +func ConsistentReadSupported() bool { + consistentListFromCacheEnabled := utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) + requestWatchProgressSupported := etcdfeature.DefaultFeatureSupportChecker.Supports(storage.RequestWatchProgress) + return consistentListFromCacheEnabled && requestWatchProgressSupported +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go index dd77febb9..0559708d2 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go @@ -176,6 +176,14 @@ var ( Help: "Counter for consistent reads from cache.", StabilityLevel: compbasemetrics.ALPHA, }, []string{"resource", "success", "fallback"}) + + StorageConsistencyCheckTotal = compbasemetrics.NewCounterVec( + &compbasemetrics.CounterOpts{ + Namespace: namespace, + Name: "storage_consistency_checks_total", + Help: "Counter for status of consistency checks between etcd and watch cache", + StabilityLevel: compbasemetrics.INTERNAL, + }, []string{"resource", "status"}) ) var registerMetrics sync.Once @@ -198,6 +206,7 @@ func Register() { legacyregistry.MustRegister(WatchCacheInitializations) legacyregistry.MustRegister(WatchCacheReadWait) legacyregistry.MustRegister(ConsistentReadTotal) + legacyregistry.MustRegister(StorageConsistencyCheckTotal) }) } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_progress.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/progress/watch_progress.go similarity index 86% rename from e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_progress.go rename to e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/progress/watch_progress.go index 087fb14e5..76fe73f13 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_progress.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/progress/watch_progress.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package cacher +package progress import ( "context" @@ -36,8 +36,8 @@ const ( progressRequestPeriod = 100 * time.Millisecond ) -func newConditionalProgressRequester(requestWatchProgress WatchProgressRequester, clock TickerFactory, contextMetadata metadata.MD) *conditionalProgressRequester { - pr := &conditionalProgressRequester{ +func NewConditionalProgressRequester(requestWatchProgress WatchProgressRequester, clock TickerFactory, contextMetadata metadata.MD) *ConditionalProgressRequester { + pr := &ConditionalProgressRequester{ clock: clock, requestWatchProgress: requestWatchProgress, contextMetadata: contextMetadata, @@ -52,9 +52,9 @@ type TickerFactory interface { NewTimer(time.Duration) clock.Timer } -// conditionalProgressRequester will request progress notification if there +// ConditionalProgressRequester will request progress notification if there // is a request waiting for watch cache to be fresh. -type conditionalProgressRequester struct { +type ConditionalProgressRequester struct { clock TickerFactory requestWatchProgress WatchProgressRequester contextMetadata metadata.MD @@ -65,7 +65,7 @@ type conditionalProgressRequester struct { stopped bool } -func (pr *conditionalProgressRequester) Run(stopCh <-chan struct{}) { +func (pr *ConditionalProgressRequester) Run(stopCh <-chan struct{}) { ctx := wait.ContextForChannel(stopCh) if pr.contextMetadata != nil { ctx = metadata.NewOutgoingContext(ctx, pr.contextMetadata) @@ -115,14 +115,14 @@ func (pr *conditionalProgressRequester) Run(stopCh <-chan struct{}) { } } -func (pr *conditionalProgressRequester) Add() { +func (pr *ConditionalProgressRequester) Add() { pr.mux.Lock() defer pr.mux.Unlock() pr.waiting += 1 pr.cond.Signal() } -func (pr *conditionalProgressRequester) Remove() { +func (pr *ConditionalProgressRequester) Remove() { pr.mux.Lock() defer pr.mux.Unlock() pr.waiting -= 1 diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/ready.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/ready.go index 012d6d585..68ff509f0 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/ready.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/ready.go @@ -20,6 +20,9 @@ import ( "context" "fmt" "sync" + "time" + + "k8s.io/utils/clock" ) type status int @@ -38,18 +41,26 @@ const ( // | ^ // └---------------------------┘ type ready struct { - state status // represent the state of the variable + state status // represent the state of the variable + lastErr error generation int // represent the number of times we have transtioned to ready lock sync.RWMutex // protect the state and generation variables restartLock sync.Mutex // protect the transition from ready to pending where the channel is recreated waitCh chan struct{} // blocks until is ready or stopped + + clock clock.Clock + lastStateChangeTime time.Time } -func newReady() *ready { - return &ready{ +func newReady(c clock.Clock) *ready { + r := &ready{ waitCh: make(chan struct{}), state: Pending, + clock: c, } + r.updateLastStateChangeTimeLocked() + + return r } // done close the channel once the state is Ready or Stopped @@ -77,8 +88,7 @@ func (r *ready) waitAndReadGeneration(ctx context.Context) (int, error) { } r.lock.RLock() - switch r.state { - case Pending: + if r.state == Pending { // since we allow to switch between the states Pending and Ready // if there is a quick transition from Pending -> Ready -> Pending // a process that was waiting can get unblocked and see a Pending @@ -86,43 +96,65 @@ func (r *ready) waitAndReadGeneration(ctx context.Context) (int, error) { // avoid an inconsistent state on the system, with some processes not // waiting despite the state moved back to Pending. r.lock.RUnlock() - case Ready: - generation := r.generation - r.lock.RUnlock() - return generation, nil - case Stopped: - r.lock.RUnlock() - return 0, fmt.Errorf("apiserver cacher is stopped") - default: - r.lock.RUnlock() - return 0, fmt.Errorf("unexpected apiserver cache state: %v", r.state) + continue } + generation, err := r.readGenerationLocked() + r.lock.RUnlock() + return generation, err } } -// check returns true only if it is Ready. -func (r *ready) check() bool { - _, ok := r.checkAndReadGeneration() - return ok +// check returns the time elapsed since the state was last changed and the current value. +func (r *ready) check() (time.Duration, error) { + _, elapsed, err := r.checkAndReadGeneration() + return elapsed, err } -// checkAndReadGeneration returns the current generation and whether it is Ready. -func (r *ready) checkAndReadGeneration() (int, bool) { +// checkAndReadGeneration returns the current generation, the time elapsed since the state was last changed and the current value. +func (r *ready) checkAndReadGeneration() (int, time.Duration, error) { r.lock.RLock() defer r.lock.RUnlock() - return r.generation, r.state == Ready + generation, err := r.readGenerationLocked() + return generation, r.clock.Since(r.lastStateChangeTime), err +} + +func (r *ready) readGenerationLocked() (int, error) { + switch r.state { + case Pending: + if r.lastErr == nil { + return 0, fmt.Errorf("storage is (re)initializing") + } else { + return 0, fmt.Errorf("storage is (re)initializing: %w", r.lastErr) + } + case Ready: + return r.generation, nil + case Stopped: + return 0, fmt.Errorf("apiserver cacher is stopped") + default: + return 0, fmt.Errorf("unexpected apiserver cache state: %v", r.state) + } +} + +func (r *ready) setReady() { + r.set(true, nil) +} + +func (r *ready) setError(err error) { + r.set(false, err) } // set the state to Pending (false) or Ready (true), it does not have effect if the state is Stopped. -func (r *ready) set(ok bool) { +func (r *ready) set(ok bool, err error) { r.lock.Lock() defer r.lock.Unlock() if r.state == Stopped { return } + r.lastErr = err if ok && r.state == Pending { r.state = Ready r.generation++ + r.updateLastStateChangeTimeLocked() select { case <-r.waitCh: default: @@ -139,6 +171,7 @@ func (r *ready) set(ok bool) { default: } r.state = Pending + r.updateLastStateChangeTimeLocked() } } @@ -148,6 +181,7 @@ func (r *ready) stop() { defer r.lock.Unlock() if r.state != Stopped { r.state = Stopped + r.updateLastStateChangeTimeLocked() } select { case <-r.waitCh: @@ -155,3 +189,7 @@ func (r *ready) stop() { close(r.waitCh) } } + +func (r *ready) updateLastStateChangeTimeLocked() { + r.lastStateChangeTime = r.clock.Now() +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store.go index 8edad10a2..9ec654e7d 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store.go @@ -19,8 +19,6 @@ package cacher import ( "fmt" - "github.com/google/btree" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -75,7 +73,9 @@ type storeIndexer interface { } type orderedLister interface { - ListPrefix(prefix, continueKey string, limit int) (items []interface{}, hasMore bool) + ListPrefix(prefix, continueKey string) []interface{} + Count(prefix, continueKey string) (count int) + Clone() orderedLister } func newStoreIndexer(indexers *cache.Indexers) storeIndexer { @@ -97,12 +97,6 @@ type storeElement struct { Fields fields.Set } -func (t *storeElement) Less(than btree.Item) bool { - return t.Key < than.(*storeElement).Key -} - -var _ btree.Item = (*storeElement)(nil) - func storeElementKey(obj interface{}) (string, error) { elem, ok := obj.(*storeElement) if !ok { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store_btree.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store_btree.go index b4af96920..9908e2f64 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store_btree.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/store_btree.go @@ -18,7 +18,6 @@ package cacher import ( "fmt" - "math" "strings" "sync" @@ -44,6 +43,20 @@ type threadedStoreIndexer struct { indexer indexer } +var _ orderedLister = (*threadedStoreIndexer)(nil) + +func (si *threadedStoreIndexer) Count(prefix, continueKey string) (count int) { + si.lock.RLock() + defer si.lock.RUnlock() + return si.store.Count(prefix, continueKey) +} + +func (si *threadedStoreIndexer) Clone() orderedLister { + si.lock.RLock() + defer si.lock.RUnlock() + return si.store.Clone() +} + func (si *threadedStoreIndexer) Add(obj interface{}) error { return si.addOrUpdate(obj) } @@ -73,11 +86,11 @@ func (si *threadedStoreIndexer) Delete(obj interface{}) error { } si.lock.Lock() defer si.lock.Unlock() - oldObj := si.store.deleteElem(storeElem) - if oldObj == nil { + oldObj, existed := si.store.deleteElem(storeElem) + if !existed { return nil } - return si.indexer.updateElem(storeElem.Key, oldObj.(*storeElement), nil) + return si.indexer.updateElem(storeElem.Key, oldObj, nil) } func (si *threadedStoreIndexer) List() []interface{} { @@ -86,10 +99,10 @@ func (si *threadedStoreIndexer) List() []interface{} { return si.store.List() } -func (si *threadedStoreIndexer) ListPrefix(prefix, continueKey string, limit int) ([]interface{}, bool) { +func (si *threadedStoreIndexer) ListPrefix(prefix, continueKey string) []interface{} { si.lock.RLock() defer si.lock.RUnlock() - return si.store.ListPrefix(prefix, continueKey, limit) + return si.store.ListPrefix(prefix, continueKey) } func (si *threadedStoreIndexer) ListKeys() []string { @@ -128,12 +141,20 @@ func (si *threadedStoreIndexer) ByIndex(indexName, indexValue string) ([]interfa func newBtreeStore(degree int) btreeStore { return btreeStore{ - tree: btree.New(degree), + tree: btree.NewG(degree, func(a, b *storeElement) bool { + return a.Key < b.Key + }), } } type btreeStore struct { - tree *btree.BTree + tree *btree.BTreeG[*storeElement] +} + +func (s *btreeStore) Clone() orderedLister { + return &btreeStore{ + tree: s.tree.Clone(), + } } func (s *btreeStore) Add(obj interface{}) error { @@ -172,14 +193,14 @@ func (s *btreeStore) Delete(obj interface{}) error { return nil } -func (s *btreeStore) deleteElem(storeElem *storeElement) interface{} { +func (s *btreeStore) deleteElem(storeElem *storeElement) (*storeElement, bool) { return s.tree.Delete(storeElem) } func (s *btreeStore) List() []interface{} { items := make([]interface{}, 0, s.tree.Len()) - s.tree.Ascend(func(i btree.Item) bool { - items = append(items, i.(interface{})) + s.tree.Ascend(func(item *storeElement) bool { + items = append(items, item) return true }) return items @@ -187,8 +208,8 @@ func (s *btreeStore) List() []interface{} { func (s *btreeStore) ListKeys() []string { items := make([]string, 0, s.tree.Len()) - s.tree.Ascend(func(i btree.Item) bool { - items = append(items, i.(*storeElement).Key) + s.tree.Ascend(func(item *storeElement) bool { + items = append(items, item.Key) return true }) return items @@ -199,11 +220,8 @@ func (s *btreeStore) Get(obj interface{}) (item interface{}, exists bool, err er if !ok { return nil, false, fmt.Errorf("obj is not a storeElement") } - item = s.tree.Get(storeElem) - if item == nil { - return nil, false, nil - } - return item, true, nil + item, exists = s.tree.Get(storeElem) + return item, exists, nil } func (s *btreeStore) GetByKey(key string) (item interface{}, exists bool, err error) { @@ -225,54 +243,37 @@ func (s *btreeStore) Replace(objs []interface{}, _ string) error { // addOrUpdateLocked assumes a lock is held and is used for Add // and Update operations. func (s *btreeStore) addOrUpdateElem(storeElem *storeElement) *storeElement { - oldObj := s.tree.ReplaceOrInsert(storeElem) - if oldObj == nil { - return nil - } - return oldObj.(*storeElement) + oldObj, _ := s.tree.ReplaceOrInsert(storeElem) + return oldObj } func (s *btreeStore) getByKey(key string) (item interface{}, exists bool, err error) { keyElement := &storeElement{Key: key} - item = s.tree.Get(keyElement) - return item, item != nil, nil + item, exists = s.tree.Get(keyElement) + return item, exists, nil } -func (s *btreeStore) ListPrefix(prefix, continueKey string, limit int) ([]interface{}, bool) { - if limit < 0 { - return nil, false - } +func (s *btreeStore) ListPrefix(prefix, continueKey string) []interface{} { if continueKey == "" { continueKey = prefix } var result []interface{} - var hasMore bool - if limit == 0 { - limit = math.MaxInt - } - s.tree.AscendGreaterOrEqual(&storeElement{Key: continueKey}, func(i btree.Item) bool { - elementKey := i.(*storeElement).Key - if !strings.HasPrefix(elementKey, prefix) { + s.tree.AscendGreaterOrEqual(&storeElement{Key: continueKey}, func(item *storeElement) bool { + if !strings.HasPrefix(item.Key, prefix) { return false } - // TODO: Might be worth to lookup one more item to provide more accurate HasMore. - if len(result) >= limit { - hasMore = true - return false - } - result = append(result, i.(interface{})) + result = append(result, item) return true }) - return result, hasMore + return result } func (s *btreeStore) Count(prefix, continueKey string) (count int) { if continueKey == "" { continueKey = prefix } - s.tree.AscendGreaterOrEqual(&storeElement{Key: continueKey}, func(i btree.Item) bool { - elementKey := i.(*storeElement).Key - if !strings.HasPrefix(elementKey, prefix) { + s.tree.AscendGreaterOrEqual(&storeElement{Key: continueKey}, func(item *storeElement) bool { + if !strings.HasPrefix(item.Key, prefix) { return false } count++ @@ -391,3 +392,114 @@ func (i *indexer) delete(key, value string, index map[string]map[string]*storeEl delete(index, value) } } + +// newStoreSnapshotter returns a storeSnapshotter that stores snapshots for +// serving read requests with exact resource versions (RV) and pagination. +// +// Snapshots are created by calling Clone method on orderedLister, which is +// expected to be fast and efficient thanks to usage of B-trees. +// B-trees can create a lazy copy of the tree structure, minimizing overhead. +// +// Assuming the watch cache observes all events and snapshots cache after each of them, +// requests for a specific resource version can be served by retrieving +// the snapshot with the greatest RV less than or equal to the requested RV. +// To make snapshot retrivial efficient we need an ordered data structure, such as tree. +// +// The initial implementation uses a B-tree to achieve the following performance characteristics (n - number of snapshots stored): +// - `Add`: Adds a new snapshot. +// Complexity: O(log n). +// Executed for each watch event observed by the cache. +// - `GetLessOrEqual`: Retrieves the snapshot with the greatest RV less than or equal to the requested RV. +// Complexity: O(log n). +// Executed for each LIST request with match=Exact or continuation. +// - `RemoveLess`: Cleans up snapshots outside the watch history window. +// Complexity: O(k log n), k - number of snapshots to remove, usually only one if watch capacity was not reduced. +// Executed per watch event observed when the cache is full. +// - `Reset`: Cleans up all snapshots. +// Complexity: O(1). +// Executed when the watch cache is reinitialized. +// +// Further optimization is possible by leveraging the property that adds always +// increase the maximum RV and deletes only increase the minimum RV. +// For example, a binary search on a cyclic buffer of (RV, snapshot) +// should reduce number of allocations and improve removal complexity. +// However, this solution is more complex and is deferred for future implementation. +// +// TODO: Rewrite to use a cyclic buffer +func newStoreSnapshotter() *storeSnapshotter { + s := &storeSnapshotter{ + snapshots: btree.NewG[rvSnapshot](btreeDegree, func(a, b rvSnapshot) bool { + return a.resourceVersion < b.resourceVersion + }), + } + return s +} + +var _ Snapshotter = (*storeSnapshotter)(nil) + +type Snapshotter interface { + Reset() + GetLessOrEqual(rv uint64) (orderedLister, bool) + Add(rv uint64, indexer orderedLister) + RemoveLess(rv uint64) + Len() int +} + +type storeSnapshotter struct { + mux sync.RWMutex + snapshots *btree.BTreeG[rvSnapshot] +} + +type rvSnapshot struct { + resourceVersion uint64 + snapshot orderedLister +} + +func (s *storeSnapshotter) Reset() { + s.mux.Lock() + defer s.mux.Unlock() + s.snapshots.Clear(false) +} + +func (s *storeSnapshotter) GetLessOrEqual(rv uint64) (orderedLister, bool) { + s.mux.RLock() + defer s.mux.RUnlock() + + var result *rvSnapshot + s.snapshots.DescendLessOrEqual(rvSnapshot{resourceVersion: rv}, func(rvs rvSnapshot) bool { + result = &rvs + return false + }) + if result == nil { + return nil, false + } + return result.snapshot, true +} + +func (s *storeSnapshotter) Add(rv uint64, indexer orderedLister) { + s.mux.Lock() + defer s.mux.Unlock() + s.snapshots.ReplaceOrInsert(rvSnapshot{resourceVersion: rv, snapshot: indexer.Clone()}) +} + +func (s *storeSnapshotter) RemoveLess(rv uint64) { + s.mux.Lock() + defer s.mux.Unlock() + for s.snapshots.Len() > 0 { + oldest, ok := s.snapshots.Min() + if !ok { + break + } + if rv <= oldest.resourceVersion { + break + } + s.snapshots.DeleteMin() + } +} + +func (s *storeSnapshotter) Len() int { + s.mux.RLock() + defer s.mux.RUnlock() + + return s.snapshots.Len() +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/util.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/util.go index 63a23800f..341e256ad 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/util.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/util.go @@ -17,7 +17,9 @@ limitations under the License. package cacher import ( + "math" "strings" + "time" ) // hasPathPrefix returns true if the string matches pathPrefix exactly, or if is prefixed with pathPrefix at a path segment boundary @@ -44,3 +46,11 @@ func hasPathPrefix(s, pathPrefix string) bool { } return false } + +// calculateRetryAfterForUnreadyCache calculates the retry duration based on the cache downtime. +func calculateRetryAfterForUnreadyCache(downtime time.Duration) int { + factor := 0.06 + result := math.Exp(factor * downtime.Seconds()) + result = math.Min(30, math.Max(1, result)) + return int(result) +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go index 541988b31..967a60c9b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go @@ -25,6 +25,7 @@ import ( "time" "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,8 +33,9 @@ import ( "k8s.io/apimachinery/pkg/watch" "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/storage" + "k8s.io/apiserver/pkg/storage/cacher/delegator" "k8s.io/apiserver/pkg/storage/cacher/metrics" - etcdfeature "k8s.io/apiserver/pkg/storage/feature" + "k8s.io/apiserver/pkg/storage/cacher/progress" utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/client-go/tools/cache" "k8s.io/component-base/tracing" @@ -52,17 +54,11 @@ const ( // after receiving a 'too high resource version' error. resourceVersionTooHighRetrySeconds = 1 - // eventFreshDuration is time duration of events we want to keep. - // We set it to `defaultBookmarkFrequency` plus epsilon to maximize - // chances that last bookmark was sent within kept history, at the - // same time, minimizing the needed memory usage. - eventFreshDuration = 75 * time.Second - // defaultLowerBoundCapacity is a default value for event cache capacity's lower bound. // TODO: Figure out, to what value we can decreased it. defaultLowerBoundCapacity = 100 - // defaultUpperBoundCapacity should be able to keep eventFreshDuration of history. + // defaultUpperBoundCapacity should be able to keep the required history. defaultUpperBoundCapacity = 100 * 1024 ) @@ -142,6 +138,9 @@ type watchCache struct { // for testing timeouts. clock clock.Clock + // eventFreshDuration defines the minimum watch history watchcache will store. + eventFreshDuration time.Duration + // An underlying storage.Versioner. versioner storage.Versioner @@ -153,7 +152,10 @@ type watchCache struct { // Requests progress notification if there are requests waiting for watch // to be fresh - waitingUntilFresh *conditionalProgressRequester + waitingUntilFresh *progress.ConditionalProgressRequester + + // Stores previous snapshots of orderedLister to allow serving requests from previous revisions. + snapshots Snapshotter } func newWatchCache( @@ -163,15 +165,16 @@ func newWatchCache( versioner storage.Versioner, indexers *cache.Indexers, clock clock.WithTicker, + eventFreshDuration time.Duration, groupResource schema.GroupResource, - progressRequester *conditionalProgressRequester) *watchCache { + progressRequester *progress.ConditionalProgressRequester) *watchCache { wc := &watchCache{ capacity: defaultLowerBoundCapacity, keyFunc: keyFunc, getAttrsFunc: getAttrsFunc, cache: make([]*watchCacheEvent, defaultLowerBoundCapacity), lowerBoundCapacity: defaultLowerBoundCapacity, - upperBoundCapacity: defaultUpperBoundCapacity, + upperBoundCapacity: capacityUpperBound(eventFreshDuration), startIndex: 0, endIndex: 0, store: newStoreIndexer(indexers), @@ -179,10 +182,14 @@ func newWatchCache( listResourceVersion: 0, eventHandler: eventHandler, clock: clock, + eventFreshDuration: eventFreshDuration, versioner: versioner, groupResource: groupResource, waitingUntilFresh: progressRequester, } + if utilfeature.DefaultFeatureGate.Enabled(features.ListFromCacheSnapshot) { + wc.snapshots = newStoreSnapshotter() + } metrics.WatchCacheCapacity.WithLabelValues(groupResource.String()).Set(float64(wc.capacity)) wc.cond = sync.NewCond(wc.RLocker()) wc.indexValidator = wc.isIndexValidLocked @@ -190,6 +197,30 @@ func newWatchCache( return wc } +// capacityUpperBound denotes the maximum possible capacity of the watch cache +// to which it can resize. +func capacityUpperBound(eventFreshDuration time.Duration) int { + if eventFreshDuration <= DefaultEventFreshDuration { + return defaultUpperBoundCapacity + } + // eventFreshDuration determines how long the watch events are supposed + // to be stored in the watch cache. + // In very high churn situations, there is a need to store more events + // in the watch cache, hence it would have to be upsized accordingly. + // Because of that, for larger values of eventFreshDuration, we set the + // upper bound of the watch cache's capacity proportionally to the ratio + // between eventFreshDuration and DefaultEventFreshDuration. + // Given that the watch cache size can only double, we round up that + // proportion to the next power of two. + exponent := int(math.Ceil((math.Log2(eventFreshDuration.Seconds() / DefaultEventFreshDuration.Seconds())))) + if maxExponent := int(math.Floor((math.Log2(math.MaxInt32 / defaultUpperBoundCapacity)))); exponent > maxExponent { + // Making sure that the capacity's upper bound fits in a 32-bit integer. + exponent = maxExponent + klog.Warningf("Capping watch cache capacity upper bound to %v", defaultUpperBoundCapacity< w.capacity { w.doCacheResizeLocked(capacity) } return } - if w.isCacheFullLocked() && eventTime.Sub(w.cache[(w.endIndex-w.capacity/4)%w.capacity].RecordTime) > eventFreshDuration { + if w.isCacheFullLocked() && eventTime.Sub(w.cache[(w.endIndex-w.capacity/4)%w.capacity].RecordTime) > w.eventFreshDuration { capacity := max(w.capacity/2, w.lowerBoundCapacity) if capacity < w.capacity { w.doCacheResizeLocked(capacity) @@ -452,9 +496,8 @@ func (s sortableStoreElements) Swap(i, j int) { // WaitUntilFreshAndList returns list of pointers to `storeElement` objects along // with their ResourceVersion and the name of the index, if any, that was used. -func (w *watchCache) WaitUntilFreshAndList(ctx context.Context, resourceVersion uint64, key string, matchValues []storage.MatchValue) (result []interface{}, rv uint64, index string, err error) { - requestWatchProgressSupported := etcdfeature.DefaultFeatureSupportChecker.Supports(storage.RequestWatchProgress) - if utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) && requestWatchProgressSupported && w.notFresh(resourceVersion) { +func (w *watchCache) WaitUntilFreshAndList(ctx context.Context, resourceVersion uint64, key string, opts storage.ListOptions) (resp listResp, index string, err error) { + if delegator.ConsistentReadSupported() && w.notFresh(resourceVersion) { w.waitingUntilFresh.Add() err = w.waitUntilFreshAndBlock(ctx, resourceVersion) w.waitingUntilFresh.Remove() @@ -464,32 +507,84 @@ func (w *watchCache) WaitUntilFreshAndList(ctx context.Context, resourceVersion defer w.RUnlock() if err != nil { - return result, rv, index, err + return listResp{}, "", err } - var prefixFilteredAndOrdered bool - result, rv, index, prefixFilteredAndOrdered, err = func() ([]interface{}, uint64, string, bool, error) { - // This isn't the place where we do "final filtering" - only some "prefiltering" is happening here. So the only - // requirement here is to NOT miss anything that should be returned. We can return as many non-matching items as we - // want - they will be filtered out later. The fact that we return less things is only further performance improvement. - // TODO: if multiple indexes match, return the one with the fewest items, so as to do as much filtering as possible. - for _, matchValue := range matchValues { - if result, err := w.store.ByIndex(matchValue.IndexName, matchValue.Value); err == nil { - return result, w.resourceVersion, matchValue.IndexName, false, nil + return w.list(ctx, resourceVersion, key, opts) +} + +// NOTICE: Structure follows the shouldDelegateList function in +// staging/src/k8s.io/apiserver/pkg/storage/cacher/delegator.go +func (w *watchCache) list(ctx context.Context, resourceVersion uint64, key string, opts storage.ListOptions) (resp listResp, index string, err error) { + switch opts.ResourceVersionMatch { + case metav1.ResourceVersionMatchExact: + return w.listExactRV(key, "", resourceVersion) + case metav1.ResourceVersionMatchNotOlderThan: + case "": + // Continue + if len(opts.Predicate.Continue) > 0 { + continueKey, continueRV, err := storage.DecodeContinue(opts.Predicate.Continue, key) + if err != nil { + return listResp{}, "", errors.NewBadRequest(fmt.Sprintf("invalid continue token: %v", err)) + } + if continueRV > 0 { + return w.listExactRV(key, continueKey, uint64(continueRV)) + } else { + // Continue with negative RV is a consistent read - already handled via waitUntilFreshAndBlock. + // Don't pass matchValues as they don't support continueKey + return w.listLatestRV(key, continueKey, nil) } } - if store, ok := w.store.(orderedLister); ok { - result, _ := store.ListPrefix(key, "", 0) - return result, w.resourceVersion, "", true, nil + // Legacy exact match + if opts.Predicate.Limit > 0 && len(opts.ResourceVersion) > 0 && opts.ResourceVersion != "0" { + return w.listExactRV(key, "", resourceVersion) } - return w.store.List(), w.resourceVersion, "", false, nil - }() - if !prefixFilteredAndOrdered { - result, err = filterPrefixAndOrder(key, result) - if err != nil { - return nil, 0, "", err + // Consistent Read - already handled via waitUntilFreshAndBlock + } + return w.listLatestRV(key, "", opts.Predicate.MatcherIndex(ctx)) +} + +func (w *watchCache) listExactRV(key, continueKey string, resourceVersion uint64) (resp listResp, index string, err error) { + if w.snapshots == nil { + return listResp{}, "", errors.NewResourceExpired(fmt.Sprintf("too old resource version: %d", resourceVersion)) + } + store, ok := w.snapshots.GetLessOrEqual(resourceVersion) + if !ok { + return listResp{}, "", errors.NewResourceExpired(fmt.Sprintf("too old resource version: %d", resourceVersion)) + } + items := store.ListPrefix(key, continueKey) + return listResp{ + Items: items, + ResourceVersion: resourceVersion, + }, "", nil +} + +func (w *watchCache) listLatestRV(key, continueKey string, matchValues []storage.MatchValue) (resp listResp, index string, err error) { + // This isn't the place where we do "final filtering" - only some "prefiltering" is happening here. So the only + // requirement here is to NOT miss anything that should be returned. We can return as many non-matching items as we + // want - they will be filtered out later. The fact that we return less things is only further performance improvement. + // TODO: if multiple indexes match, return the one with the fewest items, so as to do as much filtering as possible. + for _, matchValue := range matchValues { + if result, err := w.store.ByIndex(matchValue.IndexName, matchValue.Value); err == nil { + result, err = filterPrefixAndOrder(key, result) + return listResp{ + Items: result, + ResourceVersion: w.resourceVersion, + }, matchValue.IndexName, err } } - return result, w.resourceVersion, index, nil + if store, ok := w.store.(orderedLister); ok { + result := store.ListPrefix(key, continueKey) + return listResp{ + Items: result, + ResourceVersion: w.resourceVersion, + }, "", nil + } + result := w.store.List() + result, err = filterPrefixAndOrder(key, result) + return listResp{ + Items: result, + ResourceVersion: w.resourceVersion, + }, "", err } func filterPrefixAndOrder(prefix string, items []interface{}) ([]interface{}, error) { @@ -517,7 +612,7 @@ func (w *watchCache) notFresh(resourceVersion uint64) bool { // WaitUntilFreshAndGet returns a pointers to object. func (w *watchCache) WaitUntilFreshAndGet(ctx context.Context, resourceVersion uint64, key string) (interface{}, bool, uint64, error) { var err error - if utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) && w.notFresh(resourceVersion) { + if delegator.ConsistentReadSupported() && w.notFresh(resourceVersion) { w.waitingUntilFresh.Add() err = w.waitUntilFreshAndBlock(ctx, resourceVersion) w.waitingUntilFresh.Remove() @@ -600,6 +695,12 @@ func (w *watchCache) Replace(objs []interface{}, resourceVersion string) error { if err := w.store.Replace(toReplace, resourceVersion); err != nil { return err } + if w.snapshots != nil { + w.snapshots.Reset() + if orderedLister, ordered := w.store.(orderedLister); ordered { + w.snapshots.Add(version, orderedLister) + } + } w.listResourceVersion = version w.resourceVersion = version if w.onReplace != nil { @@ -660,7 +761,7 @@ func (w *watchCache) suggestedWatchChannelSize(indexExists, triggerUsed bool) in // We don't have an exact data, but given we store updates from // the last , we approach it by dividing the // capacity by the length of the history window. - chanSize := int(math.Ceil(float64(w.currentCapacity()) / eventFreshDuration.Seconds())) + chanSize := int(math.Ceil(float64(w.currentCapacity()) / w.eventFreshDuration.Seconds())) // Finally we adjust the size to avoid ending with too low or // to large values. @@ -751,7 +852,7 @@ func (w *watchCache) getAllEventsSinceLocked(resourceVersion uint64, key string, // that covers the entire storage state. // This function assumes to be called under the watchCache lock. func (w *watchCache) getIntervalFromStoreLocked(key string, matchesSingle bool) (*watchCacheInterval, error) { - ci, err := newCacheIntervalFromStore(w.resourceVersion, w.store, w.getAttrsFunc, key, matchesSingle) + ci, err := newCacheIntervalFromStore(w.resourceVersion, w.store, key, matchesSingle) if err != nil { return nil, err } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go index 4920022cd..b74b3ca91 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go @@ -21,9 +21,6 @@ import ( "sort" "sync" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" ) @@ -106,7 +103,6 @@ type watchCacheInterval struct { initialEventsEndBookmark *watchCacheEvent } -type attrFunc func(runtime.Object) (labels.Set, fields.Set, error) type indexerFunc func(int) *watchCacheEvent type indexValidator func(int) bool @@ -140,10 +136,9 @@ func (s sortableWatchCacheEvents) Swap(i, j int) { // returned by Next() need to be events from a List() done on the underlying store of // the watch cache. // The items returned in the interval will be sorted by Key. -func newCacheIntervalFromStore(resourceVersion uint64, store storeIndexer, getAttrsFunc attrFunc, key string, matchesSingle bool) (*watchCacheInterval, error) { +func newCacheIntervalFromStore(resourceVersion uint64, store storeIndexer, key string, matchesSingle bool) (*watchCacheInterval, error) { buffer := &watchCacheIntervalBuffer{} var allItems []interface{} - if matchesSingle { item, exists, err := store.GetByKey(key) if err != nil { @@ -162,15 +157,11 @@ func newCacheIntervalFromStore(resourceVersion uint64, store storeIndexer, getAt if !ok { return nil, fmt.Errorf("not a storeElement: %v", elem) } - objLabels, objFields, err := getAttrsFunc(elem.Object) - if err != nil { - return nil, err - } buffer.buffer[i] = &watchCacheEvent{ Type: watch.Added, Object: elem.Object, - ObjLabels: objLabels, - ObjFields: objFields, + ObjLabels: elem.Labels, + ObjFields: elem.Fields, Key: elem.Key, ResourceVersion: resourceVersion, } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/doc.go index fbdd94468..d2c5dbfc4 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Interfaces for database-related operations. -package storage // import "k8s.io/apiserver/pkg/storage" +package storage diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/errors/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/errors/doc.go index bbc65d389..e6347ba86 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/errors/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/errors/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package storage provides conversion of storage errors to API errors. -package errors // import "k8s.io/apiserver/pkg/storage/errors" +package errors diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/store.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/store.go index f38b160aa..ee5f3d676 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/store.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/store.go @@ -22,6 +22,7 @@ import ( "fmt" "path" "reflect" + "strconv" "strings" "time" @@ -32,9 +33,10 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/conversion" + "k8s.io/apimachinery/pkg/fields" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" @@ -84,6 +86,9 @@ type store struct { leaseManager *leaseManager decoder Decoder listErrAggrFactory func() ListErrorAggregator + + resourcePrefix string + newListFunc func() runtime.Object } func (s *store) RequestWatchProgress(ctx context.Context) error { @@ -185,10 +190,13 @@ func newStore(c *kubernetes.Client, codec runtime.Codec, newFunc, newListFunc fu leaseManager: newDefaultLeaseManager(c.Client, leaseManagerConfig), decoder: decoder, listErrAggrFactory: listErrAggrFactory, + + resourcePrefix: resourcePrefix, + newListFunc: newListFunc, } w.getCurrentStorageRV = func(ctx context.Context) (uint64, error) { - return storage.GetCurrentResourceVersionFromStorage(ctx, s, newListFunc, resourcePrefix, w.objectType) + return s.GetCurrentResourceVersion(ctx) } if utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) || utilfeature.DefaultFeatureGate.Enabled(features.WatchList) { etcdfeature.DefaultFeatureSupportChecker.CheckClient(c.Ctx(), c, storage.RequestWatchProgress) @@ -636,45 +644,35 @@ func (s *store) ReadinessCheck() error { return nil } -// resolveGetListRev is used by GetList to resolve the rev to use in the client.KV.Get request. -func (s *store) resolveGetListRev(continueKey string, continueRV int64, opts storage.ListOptions) (int64, error) { - var withRev int64 - // Uses continueRV if this is a continuation request. - if len(continueKey) > 0 { - if len(opts.ResourceVersion) > 0 && opts.ResourceVersion != "0" { - return withRev, apierrors.NewBadRequest("specifying resource version is not allowed when using continue") - } - // If continueRV > 0, the LIST request needs a specific resource version. - // continueRV==0 is invalid. - // If continueRV < 0, the request is for the latest resource version. - if continueRV > 0 { - withRev = continueRV - } - return withRev, nil - } - // Returns 0 if ResourceVersion is not specified. - if len(opts.ResourceVersion) == 0 { - return withRev, nil - } - parsedRV, err := s.versioner.ParseResourceVersion(opts.ResourceVersion) - if err != nil { - return withRev, apierrors.NewBadRequest(fmt.Sprintf("invalid resource version: %v", err)) +func (s *store) GetCurrentResourceVersion(ctx context.Context) (uint64, error) { + emptyList := s.newListFunc() + pred := storage.SelectionPredicate{ + Label: labels.Everything(), + Field: fields.Everything(), + Limit: 1, // just in case we actually hit something } - switch opts.ResourceVersionMatch { - case metav1.ResourceVersionMatchNotOlderThan: - // The not older than constraint is checked after we get a response from etcd, - // and returnedRV is then set to the revision we get from the etcd response. - case metav1.ResourceVersionMatchExact: - withRev = int64(parsedRV) - case "": // legacy case - if opts.Recursive && opts.Predicate.Limit > 0 && parsedRV > 0 { - withRev = int64(parsedRV) - } - default: - return withRev, fmt.Errorf("unknown ResourceVersionMatch value: %v", opts.ResourceVersionMatch) + err := s.GetList(ctx, s.resourcePrefix, storage.ListOptions{Predicate: pred}, emptyList) + if err != nil { + return 0, err } - return withRev, nil + emptyListAccessor, err := meta.ListAccessor(emptyList) + if err != nil { + return 0, err + } + if emptyListAccessor == nil { + return 0, fmt.Errorf("unable to extract a list accessor from %T", emptyList) + } + + currentResourceVersion, err := strconv.Atoi(emptyListAccessor.GetResourceVersion()) + if err != nil { + return 0, err + } + + if currentResourceVersion == 0 { + return 0, fmt.Errorf("the current resource version must be greater than 0") + } + return uint64(currentResourceVersion), nil } // GetList implements storage.Interface. @@ -713,15 +711,8 @@ func (s *store) GetList(ctx context.Context, key string, opts storage.ListOption paging := opts.Predicate.Limit > 0 newItemFunc := getNewItemFunc(listObj, v) - var continueRV, withRev int64 - var continueKey string - if opts.Recursive && len(opts.Predicate.Continue) > 0 { - continueKey, continueRV, err = storage.DecodeContinue(opts.Predicate.Continue, keyPrefix) - if err != nil { - return apierrors.NewBadRequest(fmt.Sprintf("invalid continue token: %v", err)) - } - } - if withRev, err = s.resolveGetListRev(continueKey, continueRV, opts); err != nil { + withRev, continueKey, err := storage.ValidateListOptions(keyPrefix, s.versioner, opts) + if err != nil { return err } diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/watcher.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/watcher.go index abb51b07f..e2141395b 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/watcher.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/etcd3/watcher.go @@ -438,7 +438,12 @@ func (wc *watchChan) serialProcessEvents(wg *sync.WaitGroup) { for { select { case e := <-wc.incomingEventChan: - res := wc.transform(e) + res, err := wc.transform(e) + if err != nil { + wc.sendError(err) + return + } + if res == nil { continue } @@ -461,10 +466,8 @@ func (wc *watchChan) serialProcessEvents(wg *sync.WaitGroup) { func (wc *watchChan) concurrentProcessEvents(wg *sync.WaitGroup) { p := concurrentOrderedEventProcessing{ - input: wc.incomingEventChan, - processFunc: wc.transform, - output: wc.resultChan, - processingQueue: make(chan chan *watch.Event, processEventConcurrency-1), + wc: wc, + processingQueue: make(chan chan *processingResult, processEventConcurrency-1), objectType: wc.watcher.objectType, groupResource: wc.watcher.groupResource, @@ -481,12 +484,15 @@ func (wc *watchChan) concurrentProcessEvents(wg *sync.WaitGroup) { }() } -type concurrentOrderedEventProcessing struct { - input chan *event - processFunc func(*event) *watch.Event - output chan watch.Event +type processingResult struct { + event *watch.Event + err error +} - processingQueue chan chan *watch.Event +type concurrentOrderedEventProcessing struct { + wc *watchChan + + processingQueue chan chan *processingResult // Metadata for logging objectType string groupResource schema.GroupResource @@ -498,28 +504,29 @@ func (p *concurrentOrderedEventProcessing) scheduleEventProcessing(ctx context.C select { case <-ctx.Done(): return - case e = <-p.input: + case e = <-p.wc.incomingEventChan: } - processingResponse := make(chan *watch.Event, 1) + processingResponse := make(chan *processingResult, 1) select { case <-ctx.Done(): return case p.processingQueue <- processingResponse: } wg.Add(1) - go func(e *event, response chan<- *watch.Event) { + go func(e *event, response chan<- *processingResult) { defer wg.Done() + responseEvent, err := p.wc.transform(e) select { case <-ctx.Done(): - case response <- p.processFunc(e): + case response <- &processingResult{event: responseEvent, err: err}: } }(e, processingResponse) } } func (p *concurrentOrderedEventProcessing) collectEventProcessing(ctx context.Context) { - var processingResponse chan *watch.Event - var e *watch.Event + var processingResponse chan *processingResult + var r *processingResult for { select { case <-ctx.Done(): @@ -529,21 +536,25 @@ func (p *concurrentOrderedEventProcessing) collectEventProcessing(ctx context.Co select { case <-ctx.Done(): return - case e = <-processingResponse: + case r = <-processingResponse: } - if e == nil { + if r.err != nil { + p.wc.sendError(r.err) + return + } + if r.event == nil { continue } - if len(p.output) == cap(p.output) { - klog.V(3).InfoS("Fast watcher, slow processing. Probably caused by slow dispatching events to watchers", "outgoingEvents", outgoingBufSize, "objectType", p.objectType, "groupResource", p.groupResource) + if len(p.wc.resultChan) == cap(p.wc.resultChan) { + klog.V(3).InfoS("Fast watcher, slow processing. Probably caused by slow dispatching events to watchers", "outgoingEvents", outgoingBufSize, "objectType", p.wc.watcher.objectType, "groupResource", p.wc.watcher.groupResource) } // If user couldn't receive results fast enough, we also block incoming events from watcher. // Because storing events in local will cause more memory usage. // The worst case would be closing the fast watcher. select { - case <-ctx.Done(): + case p.wc.resultChan <- *r.event: + case <-p.wc.ctx.Done(): return - case p.output <- *e: } } } @@ -561,12 +572,11 @@ func (wc *watchChan) acceptAll() bool { } // transform transforms an event into a result for user if not filtered. -func (wc *watchChan) transform(e *event) (res *watch.Event) { +func (wc *watchChan) transform(e *event) (res *watch.Event, err error) { curObj, oldObj, err := wc.prepareObjs(e) if err != nil { klog.Errorf("failed to prepare current and previous objects: %v", err) - wc.sendError(err) - return nil + return nil, err } switch { @@ -574,12 +584,11 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { object := wc.watcher.newFunc() if err := wc.watcher.versioner.UpdateObject(object, uint64(e.rev)); err != nil { klog.Errorf("failed to propagate object version: %v", err) - return nil + return nil, fmt.Errorf("failed to propagate object resource version: %w", err) } if e.isInitialEventsEndBookmark { if err := storage.AnnotateInitialEventsEndBookmark(object); err != nil { - wc.sendError(fmt.Errorf("error while accessing object's metadata gr: %v, type: %v, obj: %#v, err: %v", wc.watcher.groupResource, wc.watcher.objectType, object, err)) - return nil + return nil, fmt.Errorf("error while accessing object's metadata gr: %v, type: %v, obj: %#v, err: %w", wc.watcher.groupResource, wc.watcher.objectType, object, err) } } res = &watch.Event{ @@ -588,7 +597,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { } case e.isDeleted: if !wc.filter(oldObj) { - return nil + return nil, nil } res = &watch.Event{ Type: watch.Deleted, @@ -596,7 +605,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { } case e.isCreated: if !wc.filter(curObj) { - return nil + return nil, nil } res = &watch.Event{ Type: watch.Added, @@ -608,7 +617,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { Type: watch.Modified, Object: curObj, } - return res + return res, nil } curObjPasses := wc.filter(curObj) oldObjPasses := wc.filter(oldObj) @@ -630,7 +639,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { } } } - return res + return res, nil } func transformErrorToEvent(err error) *watch.Event { diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/interfaces.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/interfaces.go index 3932f0cae..0befb3fc6 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/interfaces.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/interfaces.go @@ -20,6 +20,7 @@ import ( "context" "fmt" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -262,6 +263,10 @@ type Interface interface { // TODO: Remove when storage.Interface will be separate from etc3.store. // Deprecated: Added temporarily to simplify exposing RequestProgress for watch cache. RequestWatchProgress(ctx context.Context) error + + // GetCurrentResourceVersion gets the current resource version from etcd. + // This method issues an empty list request and reads only the ResourceVersion from the object metadata + GetCurrentResourceVersion(ctx context.Context) (uint64, error) } // GetOptions provides the options that may be provided for storage get operations. @@ -325,3 +330,43 @@ type DeleteOptions struct { // object which otherwise can not be deleted using the normal flow IgnoreStoreReadError bool } + +func ValidateListOptions(keyPrefix string, versioner Versioner, opts ListOptions) (withRev int64, continueKey string, err error) { + if opts.Recursive && len(opts.Predicate.Continue) > 0 { + continueKey, continueRV, err := DecodeContinue(opts.Predicate.Continue, keyPrefix) + if err != nil { + return 0, "", apierrors.NewBadRequest(fmt.Sprintf("invalid continue token: %v", err)) + } + if len(opts.ResourceVersion) > 0 && opts.ResourceVersion != "0" { + return 0, "", apierrors.NewBadRequest("specifying resource version is not allowed when using continue") + } + // If continueRV > 0, the LIST request needs a specific resource version. + // continueRV==0 is invalid. + // If continueRV < 0, the request is for the latest resource version. + if continueRV > 0 { + withRev = continueRV + } + return withRev, continueKey, nil + } + if len(opts.ResourceVersion) == 0 { + return withRev, "", nil + } + parsedRV, err := versioner.ParseResourceVersion(opts.ResourceVersion) + if err != nil { + return withRev, "", apierrors.NewBadRequest(fmt.Sprintf("invalid resource version: %v", err)) + } + switch opts.ResourceVersionMatch { + case metav1.ResourceVersionMatchNotOlderThan: + // The not older than constraint is checked after we get a response from etcd, + // and returnedRV is then set to the revision we get from the etcd response. + case metav1.ResourceVersionMatchExact: + withRev = int64(parsedRV) + case "": // legacy case + if opts.Recursive && opts.Predicate.Limit > 0 && parsedRV > 0 { + withRev = int64(parsedRV) + } + default: + return withRev, "", fmt.Errorf("unknown ResourceVersionMatch value: %v", opts.ResourceVersionMatch) + } + return withRev, "", nil +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/storagebackend/config.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/storagebackend/config.go index 822470778..c948d6411 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/storagebackend/config.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/storagebackend/config.go @@ -37,6 +37,7 @@ const ( DefaultCompactInterval = 5 * time.Minute DefaultDBMetricPollInterval = 30 * time.Second + DefaultEventsHistoryWindow = 75 * time.Second DefaultHealthcheckTimeout = 2 * time.Second DefaultReadinessTimeout = 2 * time.Second ) @@ -80,6 +81,8 @@ type Config struct { CountMetricPollPeriod time.Duration // DBMetricPollInterval specifies how often should storage backend metric be updated. DBMetricPollInterval time.Duration + // EventsHistoryWindow specifies minimum history duration that storage is keeping. + EventsHistoryWindow time.Duration // HealthcheckTimeout specifies the timeout used when checking health HealthcheckTimeout time.Duration // ReadycheckTimeout specifies the timeout used when checking readiness @@ -115,6 +118,7 @@ func NewDefaultConfig(prefix string, codec runtime.Codec) *Config { Codec: codec, CompactionInterval: DefaultCompactInterval, DBMetricPollInterval: DefaultDBMetricPollInterval, + EventsHistoryWindow: DefaultEventsHistoryWindow, HealthcheckTimeout: DefaultHealthcheckTimeout, ReadycheckTimeout: DefaultReadinessTimeout, LeaseManagerConfig: etcd3.NewDefaultLeaseManagerConfig(), diff --git a/e2e/vendor/k8s.io/apiserver/pkg/storage/util.go b/e2e/vendor/k8s.io/apiserver/pkg/storage/util.go index 1aca351d9..bb231df30 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/storage/util.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/storage/util.go @@ -17,16 +17,12 @@ limitations under the License. package storage import ( - "context" "fmt" - "strconv" "sync/atomic" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/validation/path" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" ) @@ -81,45 +77,6 @@ func (hwm *HighWaterMark) Update(current int64) bool { } } -// GetCurrentResourceVersionFromStorage gets the current resource version from the underlying storage engine. -// This method issues an empty list request and reads only the ResourceVersion from the object metadata -func GetCurrentResourceVersionFromStorage(ctx context.Context, storage Interface, newListFunc func() runtime.Object, resourcePrefix, objectType string) (uint64, error) { - if storage == nil { - return 0, fmt.Errorf("storage wasn't provided for %s", objectType) - } - if newListFunc == nil { - return 0, fmt.Errorf("newListFunction wasn't provided for %s", objectType) - } - emptyList := newListFunc() - pred := SelectionPredicate{ - Label: labels.Everything(), - Field: fields.Everything(), - Limit: 1, // just in case we actually hit something - } - - err := storage.GetList(ctx, resourcePrefix, ListOptions{Predicate: pred}, emptyList) - if err != nil { - return 0, err - } - emptyListAccessor, err := meta.ListAccessor(emptyList) - if err != nil { - return 0, err - } - if emptyListAccessor == nil { - return 0, fmt.Errorf("unable to extract a list accessor from %T", emptyList) - } - - currentResourceVersion, err := strconv.Atoi(emptyListAccessor.GetResourceVersion()) - if err != nil { - return 0, err - } - - if currentResourceVersion == 0 { - return 0, fmt.Errorf("the current resource version must be greater than 0") - } - return uint64(currentResourceVersion), nil -} - // AnnotateInitialEventsEndBookmark adds a special annotation to the given object // which indicates that the initial events have been sent. // diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/registry.go b/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/registry.go new file mode 100644 index 000000000..4110db43d --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/registry.go @@ -0,0 +1,53 @@ +/* +Copyright 2025 The Kubernetes 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 compatibility + +import ( + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + utilfeature "k8s.io/apiserver/pkg/util/feature" + basecompatibility "k8s.io/component-base/compatibility" +) + +// DefaultComponentGlobalsRegistry is the global var to store the effective versions and feature gates for all components for easy access. +// Example usage: +// // register the component effective version and feature gate first +// wardleEffectiveVersion := basecompatibility.NewEffectiveVersion("1.2") +// wardleFeatureGate := featuregate.NewFeatureGate() +// utilruntime.Must(compatibility.DefaultComponentGlobalsRegistry.Register(apiserver.WardleComponentName, wardleEffectiveVersion, wardleFeatureGate, false)) +// +// cmd := &cobra.Command{ +// ... +// // call DefaultComponentGlobalsRegistry.Set() in PersistentPreRunE to ensure the feature gates are set based on emulation version right after parsing the flags. +// PersistentPreRunE: func(*cobra.Command, []string) error { +// if err := compatibility.DefaultComponentGlobalsRegistry.Set(); err != nil { +// return err +// } +// ... +// }, +// RunE: func(c *cobra.Command, args []string) error { +// // call compatibility.DefaultComponentGlobalsRegistry.Validate() somewhere +// }, +// } +// +// flags := cmd.Flags() +// // add flags +// compatibility.DefaultComponentGlobalsRegistry.AddFlags(flags) +var DefaultComponentGlobalsRegistry basecompatibility.ComponentGlobalsRegistry = basecompatibility.NewComponentGlobalsRegistry() + +func init() { + utilruntime.Must(DefaultComponentGlobalsRegistry.Register(basecompatibility.DefaultKubeComponent, DefaultBuildEffectiveVersion(), utilfeature.DefaultMutableFeatureGate)) +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/version.go b/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/version.go new file mode 100644 index 000000000..2c829d5c1 --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/compatibility/version.go @@ -0,0 +1,65 @@ +/* +Copyright 2025 The Kubernetes 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 compatibility + +import ( + "k8s.io/apimachinery/pkg/util/version" + basecompatibility "k8s.io/component-base/compatibility" + baseversion "k8s.io/component-base/version" +) + +// minimumKubeEmulationVersion is the first release emulation version is introduced, +// so the emulation version cannot go lower than that. +var minimumKubeEmulationVersion *version.Version = version.MajorMinor(1, 31) + +// DefaultBuildEffectiveVersion returns the MutableEffectiveVersion based on the +// current build information. +func DefaultBuildEffectiveVersion() basecompatibility.MutableEffectiveVersion { + binaryVersion := defaultBuildBinaryVersion() + useDefaultBuildBinaryVersion := true + // fall back to the hard coded kube version only when the git tag is not available for local unit tests. + if binaryVersion.Major() == 0 && binaryVersion.Minor() == 0 { + useDefaultBuildBinaryVersion = false + binaryVersion = version.MustParse(baseversion.DefaultKubeBinaryVersion) + } + versionFloor := kubeEffectiveVersionFloors(binaryVersion) + return basecompatibility.NewEffectiveVersion(binaryVersion, useDefaultBuildBinaryVersion, versionFloor, versionFloor) +} + +func kubeEffectiveVersionFloors(binaryVersion *version.Version) *version.Version { + // both emulationVersion and minCompatibilityVersion can be set to binaryVersion - 3 + versionFloor := binaryVersion.WithPatch(0).SubtractMinor(3) + if versionFloor.LessThan(minimumKubeEmulationVersion) { + versionFloor = minimumKubeEmulationVersion + } + return versionFloor +} + +// DefaultKubeEffectiveVersionForTest returns the MutableEffectiveVersion based on the +// latest K8s release hardcoded in DefaultKubeBinaryVersion. +// DefaultKubeBinaryVersion is hard coded because defaultBuildBinaryVersion would return 0.0 when test is run without a git tag. +// We do not enforce the N-3..N emulation version range in tests so that the tests would not automatically fail when there is a version bump. +// Only used in tests. +func DefaultKubeEffectiveVersionForTest() basecompatibility.MutableEffectiveVersion { + binaryVersion := version.MustParse(baseversion.DefaultKubeBinaryVersion) + return basecompatibility.NewEffectiveVersion(binaryVersion, false, version.MustParse("0.0"), version.MustParse("0.0")) +} + +func defaultBuildBinaryVersion() *version.Version { + verInfo := baseversion.Get() + return version.MustParse(verInfo.String()) +} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go index c707884e1..652ef57ab 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go @@ -28,7 +28,7 @@ import ( "sync" "time" - "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp" //nolint:depguard apiequality "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/doc.go index 0cbe499cd..fc30ebfd5 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/doc.go @@ -116,4 +116,4 @@ limitations under the License. // queue’s virtual start time is advanced by G. When a request // finishes being served, and the actual service time was S, the // queue’s virtual start time is decremented by G - S. -package queueset // import "k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset" +package queueset diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go index a9e76141e..6e46e2d59 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go @@ -19,15 +19,11 @@ package request import ( "math" "net/http" - "net/url" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" apirequest "k8s.io/apiserver/pkg/endpoints/request" - "k8s.io/apiserver/pkg/features" - "k8s.io/apiserver/pkg/storage" - etcdfeature "k8s.io/apiserver/pkg/storage/feature" - utilfeature "k8s.io/apiserver/pkg/util/feature" + "k8s.io/apiserver/pkg/storage/cacher/delegator" "k8s.io/klog/v2" ) @@ -86,8 +82,13 @@ func (e *listWorkEstimator) estimate(r *http.Request, flowSchemaName, priorityLe return WorkEstimate{InitialSeats: e.config.MinimumSeats} } } - - isListFromCache := requestInfo.Verb == "watch" || !shouldListFromStorage(query, &listOptions) + // TODO: Check whether watchcache is enabled. + result, err := delegator.ShouldDelegateListMeta(&listOptions, delegator.CacheWithoutSnapshots{}) + if err != nil { + return WorkEstimate{InitialSeats: maxSeats} + } + listFromStorage := result.ShouldDelegate + isListFromCache := requestInfo.Verb == "watch" || !listFromStorage numStored, err := e.countGetterFn(key(requestInfo)) switch { @@ -159,24 +160,3 @@ func key(requestInfo *apirequest.RequestInfo) string { } return groupResource.String() } - -// NOTICE: Keep in sync with shouldDelegateList function in -// -// staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go -func shouldListFromStorage(query url.Values, opts *metav1.ListOptions) bool { - resourceVersion := opts.ResourceVersion - match := opts.ResourceVersionMatch - consistentListFromCacheEnabled := utilfeature.DefaultFeatureGate.Enabled(features.ConsistentListFromCache) - requestWatchProgressSupported := etcdfeature.DefaultFeatureSupportChecker.Supports(storage.RequestWatchProgress) - - // Serve consistent reads from storage if ConsistentListFromCache is disabled - consistentReadFromStorage := resourceVersion == "" && !(consistentListFromCacheEnabled && requestWatchProgressSupported) - // Watch cache doesn't support continuations, so serve them from etcd. - hasContinuation := len(opts.Continue) > 0 - // Watch cache only supports ResourceVersionMatchNotOlderThan (default). - // see https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list - isLegacyExactMatch := opts.Limit > 0 && match == "" && len(resourceVersion) > 0 && resourceVersion != "0" - unsupportedMatch := match != "" && match != metav1.ResourceVersionMatchNotOlderThan || isLegacyExactMatch - - return consistentReadFromStorage || hasContinuation || unsupportedMatch -} diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/flushwriter/doc.go b/e2e/vendor/k8s.io/apiserver/pkg/util/flushwriter/doc.go index f81e09a29..1e7e324a1 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/util/flushwriter/doc.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/flushwriter/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package flushwriter implements a wrapper for a writer that flushes on every // write if that writer implements the io.Flusher interface -package flushwriter // import "k8s.io/apiserver/pkg/util/flushwriter" +package flushwriter diff --git a/e2e/vendor/k8s.io/apiserver/pkg/util/peerproxy/metrics/metrics.go b/e2e/vendor/k8s.io/apiserver/pkg/util/peerproxy/metrics/metrics.go index 48b89be75..9b7aee4ea 100644 --- a/e2e/vendor/k8s.io/apiserver/pkg/util/peerproxy/metrics/metrics.go +++ b/e2e/vendor/k8s.io/apiserver/pkg/util/peerproxy/metrics/metrics.go @@ -50,6 +50,11 @@ func Register() { }) } +// Only used for tests. +func Reset() { + legacyregistry.Reset() +} + // IncPeerProxiedRequest increments the # of proxied requests to peer kube-apiserver func IncPeerProxiedRequest(ctx context.Context, status string) { peerProxiedRequestsTotal.WithContext(ctx).WithLabelValues(status).Add(1) diff --git a/e2e/vendor/k8s.io/apiserver/pkg/validation/metrics.go b/e2e/vendor/k8s.io/apiserver/pkg/validation/metrics.go new file mode 100644 index 000000000..256c23c4b --- /dev/null +++ b/e2e/vendor/k8s.io/apiserver/pkg/validation/metrics.go @@ -0,0 +1,88 @@ +/* +Copyright 2025 The Kubernetes 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 validation + +import ( + "k8s.io/component-base/metrics" + "k8s.io/component-base/metrics/legacyregistry" +) + +const ( + namespace = "apiserver" // Keep it consistent; apiserver is handling it + subsystem = "validation" +) + +// ValidationMetrics is the interface for validation metrics. +type ValidationMetrics interface { + IncDeclarativeValidationMismatchMetric() + IncDeclarativeValidationPanicMetric() + Reset() +} + +var validationMetricsInstance = &validationMetrics{ + DeclarativeValidationMismatchCounter: metrics.NewCounter( + &metrics.CounterOpts{ + Namespace: namespace, + Subsystem: subsystem, + Name: "declarative_validation_mismatch_total", + Help: "Number of times declarative validation results differed from handwritten validation results for core types.", + StabilityLevel: metrics.BETA, + }, + ), + DeclarativeValidationPanicCounter: metrics.NewCounter( + &metrics.CounterOpts{ + Namespace: namespace, + Subsystem: subsystem, + Name: "declarative_validation_panic_total", + Help: "Number of times declarative validation has panicked during validation.", + StabilityLevel: metrics.BETA, + }, + ), +} + +// Metrics provides access to validation metrics. +var Metrics ValidationMetrics = validationMetricsInstance + +func init() { + legacyregistry.MustRegister(validationMetricsInstance.DeclarativeValidationMismatchCounter) + legacyregistry.MustRegister(validationMetricsInstance.DeclarativeValidationPanicCounter) +} + +type validationMetrics struct { + DeclarativeValidationMismatchCounter *metrics.Counter + DeclarativeValidationPanicCounter *metrics.Counter +} + +// Reset resets the validation metrics. +func (m *validationMetrics) Reset() { + m.DeclarativeValidationMismatchCounter.Reset() + m.DeclarativeValidationPanicCounter.Reset() +} + +// IncDeclarativeValidationMismatchMetric increments the counter for the declarative_validation_mismatch_total metric. +func (m *validationMetrics) IncDeclarativeValidationMismatchMetric() { + m.DeclarativeValidationMismatchCounter.Inc() +} + +// IncDeclarativeValidationPanicMetric increments the counter for the declarative_validation_panic_total metric. +func (m *validationMetrics) IncDeclarativeValidationPanicMetric() { + m.DeclarativeValidationPanicCounter.Inc() +} + +func ResetValidationMetricsInstance() { + validationMetricsInstance.Reset() +} diff --git a/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/buffered/doc.go b/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/buffered/doc.go index a82599e42..933eacc8d 100644 --- a/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/buffered/doc.go +++ b/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/buffered/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package buffered provides an implementation for the audit.Backend interface // that batches incoming audit events and sends batches to the delegate audit.Backend. -package buffered // import "k8s.io/apiserver/plugin/pkg/audit/buffered" +package buffered diff --git a/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/truncate/doc.go b/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/truncate/doc.go index 9392ac314..3157218eb 100644 --- a/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/truncate/doc.go +++ b/e2e/vendor/k8s.io/apiserver/plugin/pkg/audit/truncate/doc.go @@ -16,4 +16,4 @@ limitations under the License. // Package truncate provides an implementation for the audit.Backend interface // that truncates audit events and sends them to the delegate audit.Backend. -package truncate // import "k8s.io/apiserver/plugin/pkg/audit/truncate" +package truncate diff --git a/e2e/vendor/k8s.io/cloud-provider/config/doc.go b/e2e/vendor/k8s.io/cloud-provider/config/doc.go index 73322994f..25132693d 100644 --- a/e2e/vendor/k8s.io/cloud-provider/config/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/config/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +groupName=cloudcontrollermanager.config.k8s.io -package config // import "k8s.io/cloud-provider/config" +package config diff --git a/e2e/vendor/k8s.io/cloud-provider/config/v1alpha1/doc.go b/e2e/vendor/k8s.io/cloud-provider/config/v1alpha1/doc.go index 91df9c15b..4bce737d5 100644 --- a/e2e/vendor/k8s.io/cloud-provider/config/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/config/v1alpha1/doc.go @@ -29,4 +29,4 @@ limitations under the License. // +k8s:defaulter-gen=TypeMeta // +groupName=cloudcontrollermanager.config.k8s.io -package v1alpha1 // import "k8s.io/cloud-provider/config/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/cloud-provider/controllers/node/config/v1alpha1/doc.go b/e2e/vendor/k8s.io/cloud-provider/controllers/node/config/v1alpha1/doc.go index eff177166..05c1119a2 100644 --- a/e2e/vendor/k8s.io/cloud-provider/controllers/node/config/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/controllers/node/config/v1alpha1/doc.go @@ -18,4 +18,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/cloud-provider/controllers/node/config // +k8s:conversion-gen=k8s.io/cloud-provider/controllers/node/config/v1alpha1 -package v1alpha1 // import "k8s.io/cloud-provider/controllers/node/config/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/doc.go b/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/doc.go index 4c3d3aae1..919c3093d 100644 --- a/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +k8s:deepcopy-gen=package -package config // import "k8s.io/cloud-provider/controllers/service/config" +package config diff --git a/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/v1alpha1/doc.go b/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/v1alpha1/doc.go index 3d71af8af..7b9a09351 100644 --- a/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/controllers/service/config/v1alpha1/doc.go @@ -18,4 +18,4 @@ limitations under the License. // +k8s:conversion-gen=k8s.io/cloud-provider/controllers/service/config // +k8s:conversion-gen=k8s.io/cloud-provider/controllers/service/config/v1alpha1 -package v1alpha1 // import "k8s.io/cloud-provider/controllers/service/config/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/cloud-provider/doc.go b/e2e/vendor/k8s.io/cloud-provider/doc.go index 6b401e456..7192394c3 100644 --- a/e2e/vendor/k8s.io/cloud-provider/doc.go +++ b/e2e/vendor/k8s.io/cloud-provider/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package cloudprovider supplies interfaces and implementations for cloud service providers. -package cloudprovider // import "k8s.io/cloud-provider" +package cloudprovider diff --git a/e2e/vendor/k8s.io/component-base/cli/flag/tracker_flag.go b/e2e/vendor/k8s.io/component-base/cli/flag/tracker_flag.go new file mode 100644 index 000000000..a7f6efed3 --- /dev/null +++ b/e2e/vendor/k8s.io/component-base/cli/flag/tracker_flag.go @@ -0,0 +1,82 @@ +/* +Copyright 2025 The Kubernetes 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 flag + +import ( + "github.com/spf13/pflag" +) + +// TrackerValue wraps a non-boolean value and stores true in the provided boolean when it is set. +type TrackerValue struct { + value pflag.Value + provided *bool +} + +// BoolTrackerValue wraps a boolean value and stores true in the provided boolean when it is set. +type BoolTrackerValue struct { + boolValue + provided *bool +} + +type boolValue interface { + pflag.Value + IsBoolFlag() bool +} + +var _ pflag.Value = &TrackerValue{} +var _ boolValue = &BoolTrackerValue{} + +// NewTracker returns a Value wrapping the given value which stores true in the provided boolean when it is set. +func NewTracker(value pflag.Value, provided *bool) pflag.Value { + if value == nil { + panic("value must not be nil") + } + + if provided == nil { + panic("provided boolean must not be nil") + } + + if boolValue, ok := value.(boolValue); ok { + return &BoolTrackerValue{boolValue: boolValue, provided: provided} + } + return &TrackerValue{value: value, provided: provided} +} + +func (f *TrackerValue) String() string { + return f.value.String() +} + +func (f *TrackerValue) Set(value string) error { + err := f.value.Set(value) + if err == nil { + *f.provided = true + } + return err +} + +func (f *TrackerValue) Type() string { + return f.value.Type() +} + +func (f *BoolTrackerValue) Set(value string) error { + err := f.boolValue.Set(value) + if err == nil { + *f.provided = true + } + + return err +} diff --git a/e2e/vendor/k8s.io/component-base/compatibility/OWNERS b/e2e/vendor/k8s.io/component-base/compatibility/OWNERS new file mode 100644 index 000000000..fab38d807 --- /dev/null +++ b/e2e/vendor/k8s.io/component-base/compatibility/OWNERS @@ -0,0 +1,13 @@ +# See the OWNERS docs at https://go.k8s.io/owners + +# Currently assigned this directory to sig-api-machinery since this is +# an interface to the version definition in "k8s.io/apiserver/pkg/util/compatibility". + +approvers: + - sig-api-machinery-api-approvers + - jpbetz +reviewers: + - sig-api-machinery-api-reviewers + - siyuanfoundation +labels: + - sig/api-machinery diff --git a/e2e/vendor/k8s.io/component-base/featuregate/registry.go b/e2e/vendor/k8s.io/component-base/compatibility/registry.go similarity index 78% rename from e2e/vendor/k8s.io/component-base/featuregate/registry.go rename to e2e/vendor/k8s.io/component-base/compatibility/registry.go index cf35403da..cdff77b07 100644 --- a/e2e/vendor/k8s.io/component-base/featuregate/registry.go +++ b/e2e/vendor/k8s.io/component-base/compatibility/registry.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package featuregate +package compatibility import ( "fmt" @@ -26,38 +26,12 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/version" cliflag "k8s.io/component-base/cli/flag" - baseversion "k8s.io/component-base/version" + "k8s.io/component-base/featuregate" "k8s.io/klog/v2" ) -// DefaultComponentGlobalsRegistry is the global var to store the effective versions and feature gates for all components for easy access. -// Example usage: -// // register the component effective version and feature gate first -// _, _ = utilversion.DefaultComponentGlobalsRegistry.ComponentGlobalsOrRegister(utilversion.DefaultKubeComponent, utilversion.DefaultKubeEffectiveVersion(), utilfeature.DefaultMutableFeatureGate) -// wardleEffectiveVersion := utilversion.NewEffectiveVersion("1.2") -// wardleFeatureGate := featuregate.NewFeatureGate() -// utilruntime.Must(utilversion.DefaultComponentGlobalsRegistry.Register(apiserver.WardleComponentName, wardleEffectiveVersion, wardleFeatureGate, false)) -// -// cmd := &cobra.Command{ -// ... -// // call DefaultComponentGlobalsRegistry.Set() in PersistentPreRunE -// PersistentPreRunE: func(*cobra.Command, []string) error { -// if err := utilversion.DefaultComponentGlobalsRegistry.Set(); err != nil { -// return err -// } -// ... -// }, -// RunE: func(c *cobra.Command, args []string) error { -// // call utilversion.DefaultComponentGlobalsRegistry.Validate() somewhere -// }, -// } -// -// flags := cmd.Flags() -// // add flags -// utilversion.DefaultComponentGlobalsRegistry.AddFlags(flags) -var DefaultComponentGlobalsRegistry ComponentGlobalsRegistry = NewComponentGlobalsRegistry() - const ( + // DefaultKubeComponent is the component name for k8s control plane components. DefaultKubeComponent = "kube" klogLevel = 2 @@ -65,10 +39,10 @@ const ( type VersionMapping func(from *version.Version) *version.Version -// ComponentGlobals stores the global variables for a component for easy access. +// ComponentGlobals stores the global variables for a component for easy access, including feature gate and effective version. type ComponentGlobals struct { - effectiveVersion baseversion.MutableEffectiveVersion - featureGate MutableVersionedFeatureGate + effectiveVersion MutableEffectiveVersion + featureGate featuregate.MutableVersionedFeatureGate // emulationVersionMapping contains the mapping from the emulation version of this component // to the emulation version of another component. @@ -84,22 +58,24 @@ type ComponentGlobals struct { dependentMinCompatibilityVersion bool } +// ComponentGlobalsRegistry stores the global variables for different components for easy access, including feature gate and effective version of each component. type ComponentGlobalsRegistry interface { // EffectiveVersionFor returns the EffectiveVersion registered under the component. // Returns nil if the component is not registered. - EffectiveVersionFor(component string) baseversion.EffectiveVersion + EffectiveVersionFor(component string) EffectiveVersion // FeatureGateFor returns the FeatureGate registered under the component. // Returns nil if the component is not registered. - FeatureGateFor(component string) FeatureGate + FeatureGateFor(component string) featuregate.FeatureGate // Register registers the EffectiveVersion and FeatureGate for a component. // returns error if the component is already registered. - Register(component string, effectiveVersion baseversion.MutableEffectiveVersion, featureGate MutableVersionedFeatureGate) error + Register(component string, effectiveVersion MutableEffectiveVersion, featureGate featuregate.MutableVersionedFeatureGate) error // ComponentGlobalsOrRegister would return the registered global variables for the component if it already exists in the registry. // Otherwise, the provided variables would be registered under the component, and the same variables would be returned. - ComponentGlobalsOrRegister(component string, effectiveVersion baseversion.MutableEffectiveVersion, featureGate MutableVersionedFeatureGate) (baseversion.MutableEffectiveVersion, MutableVersionedFeatureGate) + ComponentGlobalsOrRegister(component string, effectiveVersion MutableEffectiveVersion, featureGate featuregate.MutableVersionedFeatureGate) (MutableEffectiveVersion, featuregate.MutableVersionedFeatureGate) // AddFlags adds flags of "--emulated-version" and "--feature-gates" AddFlags(fs *pflag.FlagSet) // Set sets the flags for all global variables for all components registered. + // A component's feature gate and effective version would not be updated until Set() is called. Set() error // SetFallback calls Set() if it has never been called. SetFallback() error @@ -118,10 +94,17 @@ type ComponentGlobalsRegistry interface { type componentGlobalsRegistry struct { componentGlobals map[string]*ComponentGlobals mutex sync.RWMutex - // list of component name to emulation version set from the flag. + // emulationVersionConfig stores the list of component name to emulation version set from the flag. + // When the `--emulated-version` flag is parsed, it would not take effect until Set() is called, + // because the emulation version needs to be set before the feature gate is set. emulationVersionConfig []string - // map of component name to the list of feature gates set from the flag. + // featureGatesConfig stores the map of component name to the list of feature gates set from the flag. + // When the `--feature-gates` flag is parsed, it would not take effect until Set() is called, + // because the emulation version needs to be set before the feature gate is set. featureGatesConfig map[string][]string + // featureGatesConfigFlags stores a pointer to the flag value, allowing other commands + // to append to the feature gates configuration rather than overwriting it + featureGatesConfigFlags *cliflag.ColonSeparatedMultimapStringString // set stores if the Set() function for the registry is already called. set bool } @@ -140,10 +123,11 @@ func (r *componentGlobalsRegistry) Reset() { r.componentGlobals = make(map[string]*ComponentGlobals) r.emulationVersionConfig = nil r.featureGatesConfig = nil + r.featureGatesConfigFlags = nil r.set = false } -func (r *componentGlobalsRegistry) EffectiveVersionFor(component string) baseversion.EffectiveVersion { +func (r *componentGlobalsRegistry) EffectiveVersionFor(component string) EffectiveVersion { r.mutex.RLock() defer r.mutex.RUnlock() globals, ok := r.componentGlobals[component] @@ -153,7 +137,7 @@ func (r *componentGlobalsRegistry) EffectiveVersionFor(component string) basever return globals.effectiveVersion } -func (r *componentGlobalsRegistry) FeatureGateFor(component string) FeatureGate { +func (r *componentGlobalsRegistry) FeatureGateFor(component string) featuregate.FeatureGate { r.mutex.RLock() defer r.mutex.RUnlock() globals, ok := r.componentGlobals[component] @@ -163,7 +147,7 @@ func (r *componentGlobalsRegistry) FeatureGateFor(component string) FeatureGate return globals.featureGate } -func (r *componentGlobalsRegistry) unsafeRegister(component string, effectiveVersion baseversion.MutableEffectiveVersion, featureGate MutableVersionedFeatureGate) error { +func (r *componentGlobalsRegistry) unsafeRegister(component string, effectiveVersion MutableEffectiveVersion, featureGate featuregate.MutableVersionedFeatureGate) error { if _, ok := r.componentGlobals[component]; ok { return fmt.Errorf("component globals of %s already registered", component) } @@ -182,7 +166,7 @@ func (r *componentGlobalsRegistry) unsafeRegister(component string, effectiveVer return nil } -func (r *componentGlobalsRegistry) Register(component string, effectiveVersion baseversion.MutableEffectiveVersion, featureGate MutableVersionedFeatureGate) error { +func (r *componentGlobalsRegistry) Register(component string, effectiveVersion MutableEffectiveVersion, featureGate featuregate.MutableVersionedFeatureGate) error { if effectiveVersion == nil { return fmt.Errorf("cannot register nil effectiveVersion") } @@ -191,7 +175,7 @@ func (r *componentGlobalsRegistry) Register(component string, effectiveVersion b return r.unsafeRegister(component, effectiveVersion, featureGate) } -func (r *componentGlobalsRegistry) ComponentGlobalsOrRegister(component string, effectiveVersion baseversion.MutableEffectiveVersion, featureGate MutableVersionedFeatureGate) (baseversion.MutableEffectiveVersion, MutableVersionedFeatureGate) { +func (r *componentGlobalsRegistry) ComponentGlobalsOrRegister(component string, effectiveVersion MutableEffectiveVersion, featureGate featuregate.MutableVersionedFeatureGate) (MutableEffectiveVersion, featuregate.MutableVersionedFeatureGate) { r.mutex.Lock() defer r.mutex.Unlock() globals, ok := r.componentGlobals[component] @@ -219,22 +203,16 @@ func (r *componentGlobalsRegistry) unsafeKnownFeatures() []string { func (r *componentGlobalsRegistry) unsafeVersionFlagOptions(isEmulation bool) []string { var vs []string for component, globals := range r.componentGlobals { - binaryVer := globals.effectiveVersion.BinaryVersion() if isEmulation { if globals.dependentEmulationVersion { continue } - // emulated version could be between binaryMajor.{binaryMinor} and binaryMajor.{binaryMinor} - // TODO: change to binaryMajor.{binaryMinor-1} and binaryMajor.{binaryMinor} in 1.32 - vs = append(vs, fmt.Sprintf("%s=%s..%s (default=%s)", component, - binaryVer.SubtractMinor(0).String(), binaryVer.String(), globals.effectiveVersion.EmulationVersion().String())) + vs = append(vs, fmt.Sprintf("%s=%s", component, globals.effectiveVersion.AllowedEmulationVersionRange())) } else { if globals.dependentMinCompatibilityVersion { continue } - // min compatibility version could be between binaryMajor.{binaryMinor-1} and binaryMajor.{binaryMinor} - vs = append(vs, fmt.Sprintf("%s=%s..%s (default=%s)", component, - binaryVer.SubtractMinor(1).String(), binaryVer.String(), globals.effectiveVersion.MinCompatibilityVersion().String())) + vs = append(vs, fmt.Sprintf("%s=%s", component, globals.effectiveVersion.AllowedMinCompatibilityVersionRange())) } } sort.Strings(vs) @@ -252,19 +230,17 @@ func (r *componentGlobalsRegistry) AddFlags(fs *pflag.FlagSet) { globals.featureGate.Close() } } - if r.emulationVersionConfig != nil || r.featureGatesConfig != nil { - klog.Warning("calling componentGlobalsRegistry.AddFlags more than once, the registry will be set by the latest flags") - } - r.emulationVersionConfig = []string{} - r.featureGatesConfig = make(map[string][]string) fs.StringSliceVar(&r.emulationVersionConfig, "emulated-version", r.emulationVersionConfig, ""+ "The versions different components emulate their capabilities (APIs, features, ...) of.\n"+ "If set, the component will emulate the behavior of this version instead of the underlying binary version.\n"+ - "Version format could only be major.minor, for example: '--emulated-version=wardle=1.2,kube=1.31'. Options are:\n"+strings.Join(r.unsafeVersionFlagOptions(true), "\n")+ - "If the component is not specified, defaults to \"kube\"") + "Version format could only be major.minor, for example: '--emulated-version=wardle=1.2,kube=1.31'.\nOptions are: "+strings.Join(r.unsafeVersionFlagOptions(true), ",")+ + "\nIf the component is not specified, defaults to \"kube\"") - fs.Var(cliflag.NewColonSeparatedMultimapStringStringAllowDefaultEmptyKey(&r.featureGatesConfig), "feature-gates", "Comma-separated list of component:key=value pairs that describe feature gates for alpha/experimental features of different components.\n"+ + if r.featureGatesConfigFlags == nil { + r.featureGatesConfigFlags = cliflag.NewColonSeparatedMultimapStringStringAllowDefaultEmptyKey(&r.featureGatesConfig) + } + fs.Var(r.featureGatesConfigFlags, "feature-gates", "Comma-separated list of component:key=value pairs that describe feature gates for alpha/experimental features of different components.\n"+ "If the component is not specified, defaults to \"kube\". This flag can be repeatedly invoked. For example: --feature-gates 'wardle:featureA=true,wardle:featureB=false' --feature-gates 'kube:featureC=true'"+ "Options are:\n"+strings.Join(r.unsafeKnownFeatures(), "\n")) } @@ -441,7 +417,7 @@ func (r *componentGlobalsRegistry) SetEmulationVersionMapping(fromComponent, toC return fmt.Errorf("EmulationVersion from %s to %s already exists", fromComponent, toComponent) } versionMapping[toComponent] = f - klog.V(klogLevel).Infof("setting the default EmulationVersion of %s based on mapping from the default EmulationVersion of %s", fromComponent, toComponent) + klog.V(klogLevel).Infof("setting the default EmulationVersion of %s based on mapping from the default EmulationVersion of %s", toComponent, fromComponent) defaultFromVersion := r.componentGlobals[fromComponent].effectiveVersion.EmulationVersion() emulationVersions, err := r.getFullEmulationVersionConfig(map[string]*version.Version{fromComponent: defaultFromVersion}) if err != nil { diff --git a/e2e/vendor/k8s.io/component-base/compatibility/version.go b/e2e/vendor/k8s.io/component-base/compatibility/version.go new file mode 100644 index 000000000..331375ff4 --- /dev/null +++ b/e2e/vendor/k8s.io/component-base/compatibility/version.go @@ -0,0 +1,239 @@ +/* +Copyright 2025 The Kubernetes 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 compatibility + +import ( + "fmt" + "sync/atomic" + + "k8s.io/apimachinery/pkg/util/version" + apimachineryversion "k8s.io/apimachinery/pkg/version" + baseversion "k8s.io/component-base/version" +) + +// EffectiveVersion stores all the version information of a component. +type EffectiveVersion interface { + // BinaryVersion is the binary version of a component. Tied to a particular binary release. + BinaryVersion() *version.Version + // EmulationVersion is the version a component emulate its capabilities (APIs, features, ...) of. + // If EmulationVersion is set to be different from BinaryVersion, the component will emulate the behavior of this version instead of the underlying binary version. + EmulationVersion() *version.Version + // MinCompatibilityVersion is the minimum version a component is compatible with (in terms of storage versions, validation rules, ...). + MinCompatibilityVersion() *version.Version + EqualTo(other EffectiveVersion) bool + String() string + Validate() []error + // AllowedEmulationVersionRange returns the string of the allowed range of emulation version. + // Used only for docs/help. + AllowedEmulationVersionRange() string + // AllowedMinCompatibilityVersionRange returns the string of the allowed range of min compatibility version. + // Used only for docs/help. + AllowedMinCompatibilityVersionRange() string + + // Info returns the version information of a component. + Info() *apimachineryversion.Info +} + +type MutableEffectiveVersion interface { + EffectiveVersion + SetEmulationVersion(emulationVersion *version.Version) + SetMinCompatibilityVersion(minCompatibilityVersion *version.Version) +} + +type effectiveVersion struct { + // When true, BinaryVersion() returns the current binary version + useDefaultBuildBinaryVersion atomic.Bool + // Holds the last binary version stored in Set() + binaryVersion atomic.Pointer[version.Version] + // If the emulationVersion is set by the users, it could only contain major and minor versions. + // In tests, emulationVersion could be the same as the binary version, or set directly, + // which can have "alpha" as pre-release to continue serving expired apis while we clean up the test. + emulationVersion atomic.Pointer[version.Version] + // minCompatibilityVersion could only contain major and minor versions. + minCompatibilityVersion atomic.Pointer[version.Version] + // emulationVersionFloor is the minimum emulationVersion allowed. No limit if nil. + emulationVersionFloor *version.Version + // minCompatibilityVersionFloor is the minimum minCompatibilityVersionFloor allowed. No limit if nil. + minCompatibilityVersionFloor *version.Version +} + +func (m *effectiveVersion) BinaryVersion() *version.Version { + if m.useDefaultBuildBinaryVersion.Load() { + return defaultBuildBinaryVersion() + } + return m.binaryVersion.Load() +} + +func (m *effectiveVersion) EmulationVersion() *version.Version { + return m.emulationVersion.Load() +} + +func (m *effectiveVersion) MinCompatibilityVersion() *version.Version { + return m.minCompatibilityVersion.Load() +} + +func (m *effectiveVersion) EqualTo(other EffectiveVersion) bool { + return m.BinaryVersion().EqualTo(other.BinaryVersion()) && m.EmulationVersion().EqualTo(other.EmulationVersion()) && m.MinCompatibilityVersion().EqualTo(other.MinCompatibilityVersion()) +} + +func (m *effectiveVersion) String() string { + if m == nil { + return "" + } + return fmt.Sprintf("{BinaryVersion: %s, EmulationVersion: %s, MinCompatibilityVersion: %s}", + m.BinaryVersion().String(), m.EmulationVersion().String(), m.MinCompatibilityVersion().String()) +} + +func majorMinor(ver *version.Version) *version.Version { + if ver == nil { + return ver + } + return version.MajorMinor(ver.Major(), ver.Minor()) +} + +func (m *effectiveVersion) SetEmulationVersion(emulationVersion *version.Version) { + m.emulationVersion.Store(majorMinor(emulationVersion)) + // set the default minCompatibilityVersion to be emulationVersion - 1 if possible + minCompatibilityVersion := majorMinor(emulationVersion.SubtractMinor(1)) + if minCompatibilityVersion.LessThan(m.minCompatibilityVersionFloor) { + minCompatibilityVersion = m.minCompatibilityVersionFloor + } + m.minCompatibilityVersion.Store(minCompatibilityVersion) +} + +// SetMinCompatibilityVersion should be called after SetEmulationVersion +func (m *effectiveVersion) SetMinCompatibilityVersion(minCompatibilityVersion *version.Version) { + m.minCompatibilityVersion.Store(majorMinor(minCompatibilityVersion)) +} + +func (m *effectiveVersion) AllowedEmulationVersionRange() string { + binaryVersion := m.BinaryVersion() + if binaryVersion == nil { + return "" + } + + // Consider patch version to be 0. + binaryVersion = version.MajorMinor(binaryVersion.Major(), binaryVersion.Minor()) + + floor := m.emulationVersionFloor + if floor == nil { + floor = version.MajorMinor(0, 0) + } + + return fmt.Sprintf("%s..%s(default:%s)", floor.String(), binaryVersion.String(), m.EmulationVersion().String()) +} + +func (m *effectiveVersion) AllowedMinCompatibilityVersionRange() string { + binaryVersion := m.BinaryVersion() + if binaryVersion == nil { + return "" + } + + // Consider patch version to be 0. + binaryVersion = version.MajorMinor(binaryVersion.Major(), binaryVersion.Minor()) + + floor := m.minCompatibilityVersionFloor + if floor == nil { + floor = version.MajorMinor(0, 0) + } + + return fmt.Sprintf("%s..%s(default:%s)", floor.String(), binaryVersion.String(), m.MinCompatibilityVersion().String()) +} + +func (m *effectiveVersion) Validate() []error { + var errs []error + // Validate only checks the major and minor versions. + binaryVersion := m.BinaryVersion().WithPatch(0) + emulationVersion := m.emulationVersion.Load() + minCompatibilityVersion := m.minCompatibilityVersion.Load() + // emulationVersion can only be between emulationVersionFloor and binaryVersion + if emulationVersion.GreaterThan(binaryVersion) || emulationVersion.LessThan(m.emulationVersionFloor) { + errs = append(errs, fmt.Errorf("emulation version %s is not between [%s, %s]", emulationVersion.String(), m.emulationVersionFloor.String(), binaryVersion.String())) + } + // minCompatibilityVersion can only be between minCompatibilityVersionFloor and emulationVersion + if minCompatibilityVersion.GreaterThan(emulationVersion) || minCompatibilityVersion.LessThan(m.minCompatibilityVersionFloor) { + errs = append(errs, fmt.Errorf("minCompatibilityVersion version %s is not between [%s, %s]", minCompatibilityVersion.String(), m.minCompatibilityVersionFloor.String(), emulationVersion.String())) + } + return errs +} + +// Info returns the version information of a component. +// If the binary version is nil, it returns nil. +func (m *effectiveVersion) Info() *apimachineryversion.Info { + binVer := m.BinaryVersion() + if binVer == nil { + return nil + } + + info := baseversion.Get() + info.Major = version.Itoa(binVer.Major()) + info.Minor = version.Itoa(binVer.Minor()) + if info.GitVersion == "" { + info.GitVersion = binVer.String() + } + + if ev := m.EmulationVersion(); ev != nil { + info.EmulationMajor = version.Itoa(ev.Major()) + info.EmulationMinor = version.Itoa(ev.Minor()) + } + + if mcv := m.MinCompatibilityVersion(); mcv != nil { + info.MinCompatibilityMajor = version.Itoa(mcv.Major()) + info.MinCompatibilityMinor = version.Itoa(mcv.Minor()) + } + + return &info +} + +// NewEffectiveVersion creates a MutableEffectiveVersion from the binaryVersion. +// If useDefaultBuildBinaryVersion is true, the call of BinaryVersion() will always return the current binary version. +// NewEffectiveVersion(binaryVersion, true) should only be used if the binary version is dynamic. +// Otherwise, use NewEffectiveVersion(binaryVersion, false) or NewEffectiveVersionFromString. +func NewEffectiveVersion(binaryVersion *version.Version, useDefaultBuildBinaryVersion bool, emulationVersionFloor, minCompatibilityVersionFloor *version.Version) MutableEffectiveVersion { + effective := &effectiveVersion{ + emulationVersionFloor: emulationVersionFloor, + minCompatibilityVersionFloor: minCompatibilityVersionFloor, + } + compatVersion := binaryVersion.SubtractMinor(1) + effective.binaryVersion.Store(binaryVersion) + effective.useDefaultBuildBinaryVersion.Store(useDefaultBuildBinaryVersion) + effective.SetEmulationVersion(binaryVersion) + effective.SetMinCompatibilityVersion(compatVersion) + return effective +} + +// NewEffectiveVersionFromString creates a MutableEffectiveVersion from the binaryVersion string. +func NewEffectiveVersionFromString(binaryVer, emulationVerFloor, minCompatibilityVerFloor string) MutableEffectiveVersion { + if binaryVer == "" { + return &effectiveVersion{} + } + binaryVersion := version.MustParse(binaryVer) + emulationVersionFloor := version.MajorMinor(0, 0) + if emulationVerFloor != "" { + emulationVersionFloor = version.MustParse(emulationVerFloor) + } + minCompatibilityVersionFloor := version.MajorMinor(0, 0) + if minCompatibilityVerFloor != "" { + minCompatibilityVersionFloor = version.MustParse(minCompatibilityVerFloor) + } + return NewEffectiveVersion(binaryVersion, false, emulationVersionFloor, minCompatibilityVersionFloor) +} + +func defaultBuildBinaryVersion() *version.Version { + verInfo := baseversion.Get() + return version.MustParse(verInfo.String()) +} diff --git a/e2e/vendor/k8s.io/component-base/config/doc.go b/e2e/vendor/k8s.io/component-base/config/doc.go index dd0a5a53a..a06a258eb 100644 --- a/e2e/vendor/k8s.io/component-base/config/doc.go +++ b/e2e/vendor/k8s.io/component-base/config/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +k8s:deepcopy-gen=package -package config // import "k8s.io/component-base/config" +package config diff --git a/e2e/vendor/k8s.io/component-base/config/v1alpha1/doc.go b/e2e/vendor/k8s.io/component-base/config/v1alpha1/doc.go index 3cd4f4292..7e4d6e890 100644 --- a/e2e/vendor/k8s.io/component-base/config/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/component-base/config/v1alpha1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +k8s:conversion-gen=k8s.io/component-base/config -package v1alpha1 // import "k8s.io/component-base/config/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/component-base/featuregate/feature_gate.go b/e2e/vendor/k8s.io/component-base/featuregate/feature_gate.go index b6f08a6cd..30e430d56 100644 --- a/e2e/vendor/k8s.io/component-base/featuregate/feature_gate.go +++ b/e2e/vendor/k8s.io/component-base/featuregate/feature_gate.go @@ -268,7 +268,6 @@ func NewVersionedFeatureGate(emulationVersion *version.Version) *featureGate { f.enabledRaw.Store(map[string]bool{}) f.emulationVersion.Store(emulationVersion) f.queriedFeatures.Store(sets.Set[Feature]{}) - klog.V(1).Infof("new feature gate with emulationVersion=%s", f.emulationVersion.Load().String()) return f } @@ -319,7 +318,6 @@ func (f *featureGate) unsafeSetFromMap(enabled map[Feature]bool, m map[string]bo // Copy existing state known := map[Feature]VersionedSpecs{} for k, v := range f.known.Load().(map[Feature]VersionedSpecs) { - sort.Sort(v) known[k] = v } @@ -422,19 +420,52 @@ func (f *featureGate) AddVersioned(features map[Feature]VersionedSpecs) error { if f.closed { return fmt.Errorf("cannot add a feature gate after adding it to the flag set") } - // Copy existing state known := f.GetAllVersioned() for name, specs := range features { - sort.Sort(specs) if existingSpec, found := known[name]; found { - sort.Sort(existingSpec) if reflect.DeepEqual(existingSpec, specs) { continue } return fmt.Errorf("feature gate %q with different spec already exists: %v", name, existingSpec) } + // Validate new specs are well-formed + var lastVersion *version.Version + var wasBeta, wasGA, wasDeprecated bool + for i, spec := range specs { + if spec.Version == nil { + return fmt.Errorf("feature %q did not provide a version", name) + } + if len(spec.Version.Components()) != 2 { + return fmt.Errorf("feature %q specified patch version: %s", name, spec.Version.String()) + + } + // gates that begin as deprecated must indicate their prior state + if i == 0 && spec.PreRelease == Deprecated && spec.Version.Minor() != 0 { + return fmt.Errorf("feature %q introduced as deprecated must provide a 1.0 entry indicating initial state", name) + } + if i > 0 { + // versions must strictly increase + if !lastVersion.LessThan(spec.Version) { + return fmt.Errorf("feature %q lists version transitions in non-increasing order (%s <= %s)", name, spec.Version, lastVersion) + } + // stability must not regress from ga --> {beta,alpha} or beta --> alpha, and + // Deprecated state must be the terminal state + switch { + case spec.PreRelease != Deprecated && wasDeprecated: + return fmt.Errorf("deprecated feature %q must not resurrect from its terminal state", name) + case spec.PreRelease == Alpha && (wasBeta || wasGA): + return fmt.Errorf("feature %q regresses stability from more stable level to %s in %s", name, spec.PreRelease, spec.Version) + case spec.PreRelease == Beta && wasGA: + return fmt.Errorf("feature %q regresses stability from more stable level to %s in %s", name, spec.PreRelease, spec.Version) + } + } + lastVersion = spec.Version + wasBeta = wasBeta || spec.PreRelease == Beta + wasGA = wasGA || spec.PreRelease == GA + wasDeprecated = wasDeprecated || spec.PreRelease == Deprecated + } known[name] = specs } diff --git a/e2e/vendor/k8s.io/component-base/logs/api/v1/doc.go b/e2e/vendor/k8s.io/component-base/logs/api/v1/doc.go index 735aecb0c..dee5335fa 100644 --- a/e2e/vendor/k8s.io/component-base/logs/api/v1/doc.go +++ b/e2e/vendor/k8s.io/component-base/logs/api/v1/doc.go @@ -29,4 +29,4 @@ limitations under the License. // The LoggingAlphaOptions and LoggingBetaOptions feature gates control whether // these unstable features can get enabled. This can be used to ensure that // command invocations do not accidentally rely on unstable features. -package v1 // import "k8s.io/component-base/logs/api/v1" +package v1 diff --git a/e2e/vendor/k8s.io/component-base/logs/api/v1/kube_features.go b/e2e/vendor/k8s.io/component-base/logs/api/v1/kube_features.go index 4cfc69f89..fe23f5793 100644 --- a/e2e/vendor/k8s.io/component-base/logs/api/v1/kube_features.go +++ b/e2e/vendor/k8s.io/component-base/logs/api/v1/kube_features.go @@ -17,6 +17,7 @@ limitations under the License. package v1 import ( + "k8s.io/apimachinery/pkg/util/version" "k8s.io/component-base/featuregate" ) @@ -31,17 +32,16 @@ const ( // used by a call chain. ContextualLogging featuregate.Feature = "ContextualLogging" - // contextualLoggingDefault is now true because the feature reached beta - // and performance comparisons showed no relevant degradation when - // enabling it. - contextualLoggingDefault = true - // Allow fine-tuning of experimental, alpha-quality logging options. // // Per https://groups.google.com/g/kubernetes-sig-architecture/c/Nxsc7pfe5rw/m/vF2djJh0BAAJ // we want to avoid a proliferation of feature gates. This feature gate: // - will guard *a group* of logging options whose quality level is alpha. // - will never graduate to beta or stable. + // + // IMPORTANT: Unlike typical feature gates, LoggingAlphaOptions is NOT affected by + // emulation version changes. Its behavior remains constant regardless of the + // emulation version being used. LoggingAlphaOptions featuregate.Feature = "LoggingAlphaOptions" // Allow fine-tuning of experimental, beta-quality logging options. @@ -51,22 +51,32 @@ const ( // - will guard *a group* of logging options whose quality level is beta. // - is thus *introduced* as beta // - will never graduate to stable. + // + // IMPORTANT: Unlike typical feature gates, LoggingBetaOptions is NOT affected by + // emulation version changes. Its behavior remains constant regardless of the + // emulation version being used. LoggingBetaOptions featuregate.Feature = "LoggingBetaOptions" // Stable logging options. Always enabled. LoggingStableOptions featuregate.Feature = "LoggingStableOptions" ) -func featureGates() map[featuregate.Feature]featuregate.FeatureSpec { - return map[featuregate.Feature]featuregate.FeatureSpec{ - ContextualLogging: {Default: contextualLoggingDefault, PreRelease: featuregate.Beta}, - - LoggingAlphaOptions: {Default: false, PreRelease: featuregate.Alpha}, - LoggingBetaOptions: {Default: true, PreRelease: featuregate.Beta}, +func featureGates() map[featuregate.Feature]featuregate.VersionedSpecs { + return map[featuregate.Feature]featuregate.VersionedSpecs{ + ContextualLogging: { + {Version: version.MustParse("1.24"), Default: false, PreRelease: featuregate.Alpha}, + {Version: version.MustParse("1.30"), Default: true, PreRelease: featuregate.Beta}, + }, + LoggingAlphaOptions: { + {Version: version.MustParse("1.24"), Default: false, PreRelease: featuregate.Alpha}, + }, + LoggingBetaOptions: { + {Version: version.MustParse("1.24"), Default: true, PreRelease: featuregate.Beta}, + }, } } // AddFeatureGates adds all feature gates used by this package. -func AddFeatureGates(mutableFeatureGate featuregate.MutableFeatureGate) error { - return mutableFeatureGate.Add(featureGates()) +func AddFeatureGates(mutableFeatureGate featuregate.MutableVersionedFeatureGate) error { + return mutableFeatureGate.AddVersioned(featureGates()) } diff --git a/e2e/vendor/k8s.io/component-base/logs/api/v1/options.go b/e2e/vendor/k8s.io/component-base/logs/api/v1/options.go index 754443bf6..95c0a2cba 100644 --- a/e2e/vendor/k8s.io/component-base/logs/api/v1/options.go +++ b/e2e/vendor/k8s.io/component-base/logs/api/v1/options.go @@ -27,7 +27,7 @@ import ( "sync/atomic" "time" - "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp" //nolint:depguard "github.com/spf13/pflag" "k8s.io/klog/v2" @@ -153,7 +153,7 @@ func Validate(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldP errs = append(errs, field.Invalid(fldPath.Child("format"), c.Format, "Unsupported log format")) } else if format != nil { if format.feature != LoggingStableOptions { - enabled := featureGates()[format.feature].Default + enabled := featureGates()[format.feature][len(featureGates()[format.feature])-1].Default if featureGate != nil { enabled = featureGate.Enabled(format.feature) } @@ -228,7 +228,7 @@ func apply(c *LoggingConfiguration, options *LoggingOptions, featureGate feature p := ¶meters{ C: c, Options: options, - ContextualLoggingEnabled: contextualLoggingDefault, + ContextualLoggingEnabled: true, } if featureGate != nil { p.ContextualLoggingEnabled = featureGate.Enabled(ContextualLogging) diff --git a/e2e/vendor/k8s.io/component-base/metrics/testutil/testutil.go b/e2e/vendor/k8s.io/component-base/metrics/testutil/testutil.go index b00f949c3..d023a0dea 100644 --- a/e2e/vendor/k8s.io/component-base/metrics/testutil/testutil.go +++ b/e2e/vendor/k8s.io/component-base/metrics/testutil/testutil.go @@ -20,7 +20,9 @@ import ( "fmt" "io" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" + dto "github.com/prometheus/client_model/go" apimachineryversion "k8s.io/apimachinery/pkg/version" "k8s.io/component-base/metrics" @@ -33,6 +35,14 @@ type TB interface { Fatalf(format string, args ...any) } +// MetricFamily is a type alias which enables writing gatherers in tests +// without importing prometheus directly (https://github.com/kubernetes/kubernetes/issues/99876). +type MetricFamily = dto.MetricFamily + +// GathererFunc is a type alias which enables writing gatherers as a function in tests +// without importing prometheus directly (https://github.com/kubernetes/kubernetes/issues/99876). +type GathererFunc = prometheus.GathererFunc + // CollectAndCompare registers the provided Collector with a newly created // pedantic Registry. It then does the same as GatherAndCompare, gathering the // metrics from the pedantic Registry. diff --git a/e2e/vendor/k8s.io/component-base/tracing/api/v1/doc.go b/e2e/vendor/k8s.io/component-base/tracing/api/v1/doc.go index ffe36aef6..48e6e20f3 100644 --- a/e2e/vendor/k8s.io/component-base/tracing/api/v1/doc.go +++ b/e2e/vendor/k8s.io/component-base/tracing/api/v1/doc.go @@ -26,4 +26,4 @@ limitations under the License. // The "v1" package name is just a reminder that API compatibility rules apply, // not an indication of the stability of all features covered by it. -package v1 // import "k8s.io/component-base/tracing/api/v1" +package v1 diff --git a/e2e/vendor/k8s.io/component-base/version/base.go b/e2e/vendor/k8s.io/component-base/version/base.go index 46500118a..d1810b727 100644 --- a/e2e/vendor/k8s.io/component-base/version/base.go +++ b/e2e/vendor/k8s.io/component-base/version/base.go @@ -66,5 +66,5 @@ const ( // DefaultKubeBinaryVersion is the hard coded k8 binary version based on the latest K8s release. // It is supposed to be consistent with gitMajor and gitMinor, except for local tests, where gitMajor and gitMinor are "". // Should update for each minor release! - DefaultKubeBinaryVersion = "1.32" + DefaultKubeBinaryVersion = "1.33" ) diff --git a/e2e/vendor/k8s.io/component-base/version/version.go b/e2e/vendor/k8s.io/component-base/version/version.go index 99d368534..c71ccf196 100644 --- a/e2e/vendor/k8s.io/component-base/version/version.go +++ b/e2e/vendor/k8s.io/component-base/version/version.go @@ -19,43 +19,14 @@ package version import ( "fmt" "runtime" - "sync/atomic" - "k8s.io/apimachinery/pkg/util/version" apimachineryversion "k8s.io/apimachinery/pkg/version" ) -type EffectiveVersion interface { - BinaryVersion() *version.Version - EmulationVersion() *version.Version - MinCompatibilityVersion() *version.Version - EqualTo(other EffectiveVersion) bool - String() string - Validate() []error -} - -type MutableEffectiveVersion interface { - EffectiveVersion - Set(binaryVersion, emulationVersion, minCompatibilityVersion *version.Version) - SetEmulationVersion(emulationVersion *version.Version) - SetMinCompatibilityVersion(minCompatibilityVersion *version.Version) -} - -type effectiveVersion struct { - // When true, BinaryVersion() returns the current binary version - useDefaultBuildBinaryVersion atomic.Bool - // Holds the last binary version stored in Set() - binaryVersion atomic.Pointer[version.Version] - // If the emulationVersion is set by the users, it could only contain major and minor versions. - // In tests, emulationVersion could be the same as the binary version, or set directly, - // which can have "alpha" as pre-release to continue serving expired apis while we clean up the test. - emulationVersion atomic.Pointer[version.Version] - // minCompatibilityVersion could only contain major and minor versions. - minCompatibilityVersion atomic.Pointer[version.Version] -} - // Get returns the overall codebase version. It's for detecting // what code a binary was built from. +// The caller should use BinaryMajor and BinaryMinor to determine +// the binary version. The Major and Minor fields are still set by git version for backwards compatibility. func Get() apimachineryversion.Info { // These variables typically come from -ldflags settings and in // their absence fallback to the settings in ./base.go @@ -71,129 +42,3 @@ func Get() apimachineryversion.Info { Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), } } - -func (m *effectiveVersion) BinaryVersion() *version.Version { - if m.useDefaultBuildBinaryVersion.Load() { - return defaultBuildBinaryVersion() - } - return m.binaryVersion.Load() -} - -func (m *effectiveVersion) EmulationVersion() *version.Version { - ver := m.emulationVersion.Load() - if ver != nil { - // Emulation version can have "alpha" as pre-release to continue serving expired apis while we clean up the test. - // The pre-release should not be accessible to the users. - return ver.WithPreRelease(m.BinaryVersion().PreRelease()) - } - return ver -} - -func (m *effectiveVersion) MinCompatibilityVersion() *version.Version { - return m.minCompatibilityVersion.Load() -} - -func (m *effectiveVersion) EqualTo(other EffectiveVersion) bool { - return m.BinaryVersion().EqualTo(other.BinaryVersion()) && m.EmulationVersion().EqualTo(other.EmulationVersion()) && m.MinCompatibilityVersion().EqualTo(other.MinCompatibilityVersion()) -} - -func (m *effectiveVersion) String() string { - if m == nil { - return "" - } - return fmt.Sprintf("{BinaryVersion: %s, EmulationVersion: %s, MinCompatibilityVersion: %s}", - m.BinaryVersion().String(), m.EmulationVersion().String(), m.MinCompatibilityVersion().String()) -} - -func majorMinor(ver *version.Version) *version.Version { - if ver == nil { - return ver - } - return version.MajorMinor(ver.Major(), ver.Minor()) -} - -func (m *effectiveVersion) Set(binaryVersion, emulationVersion, minCompatibilityVersion *version.Version) { - m.binaryVersion.Store(binaryVersion) - m.useDefaultBuildBinaryVersion.Store(false) - m.emulationVersion.Store(majorMinor(emulationVersion)) - m.minCompatibilityVersion.Store(majorMinor(minCompatibilityVersion)) -} - -func (m *effectiveVersion) SetEmulationVersion(emulationVersion *version.Version) { - m.emulationVersion.Store(majorMinor(emulationVersion)) -} - -func (m *effectiveVersion) SetMinCompatibilityVersion(minCompatibilityVersion *version.Version) { - m.minCompatibilityVersion.Store(majorMinor(minCompatibilityVersion)) -} - -func (m *effectiveVersion) Validate() []error { - var errs []error - // Validate only checks the major and minor versions. - binaryVersion := m.BinaryVersion().WithPatch(0) - emulationVersion := m.emulationVersion.Load() - minCompatibilityVersion := m.minCompatibilityVersion.Load() - - // emulationVersion can only be 1.{binaryMinor-1}...1.{binaryMinor}. - maxEmuVer := binaryVersion - minEmuVer := binaryVersion.SubtractMinor(1) - if emulationVersion.GreaterThan(maxEmuVer) || emulationVersion.LessThan(minEmuVer) { - errs = append(errs, fmt.Errorf("emulation version %s is not between [%s, %s]", emulationVersion.String(), minEmuVer.String(), maxEmuVer.String())) - } - // minCompatibilityVersion can only be 1.{binaryMinor-1} for alpha. - maxCompVer := binaryVersion.SubtractMinor(1) - minCompVer := binaryVersion.SubtractMinor(1) - if minCompatibilityVersion.GreaterThan(maxCompVer) || minCompatibilityVersion.LessThan(minCompVer) { - errs = append(errs, fmt.Errorf("minCompatibilityVersion version %s is not between [%s, %s]", minCompatibilityVersion.String(), minCompVer.String(), maxCompVer.String())) - } - return errs -} - -func newEffectiveVersion(binaryVersion *version.Version, useDefaultBuildBinaryVersion bool) MutableEffectiveVersion { - effective := &effectiveVersion{} - compatVersion := binaryVersion.SubtractMinor(1) - effective.Set(binaryVersion, binaryVersion, compatVersion) - effective.useDefaultBuildBinaryVersion.Store(useDefaultBuildBinaryVersion) - return effective -} - -func NewEffectiveVersion(binaryVer string) MutableEffectiveVersion { - if binaryVer == "" { - return &effectiveVersion{} - } - binaryVersion := version.MustParse(binaryVer) - return newEffectiveVersion(binaryVersion, false) -} - -func defaultBuildBinaryVersion() *version.Version { - verInfo := Get() - return version.MustParse(verInfo.String()).WithInfo(verInfo) -} - -// DefaultBuildEffectiveVersion returns the MutableEffectiveVersion based on the -// current build information. -func DefaultBuildEffectiveVersion() MutableEffectiveVersion { - binaryVersion := defaultBuildBinaryVersion() - if binaryVersion.Major() == 0 && binaryVersion.Minor() == 0 { - return DefaultKubeEffectiveVersion() - } - return newEffectiveVersion(binaryVersion, true) -} - -// DefaultKubeEffectiveVersion returns the MutableEffectiveVersion based on the -// latest K8s release. -func DefaultKubeEffectiveVersion() MutableEffectiveVersion { - binaryVersion := version.MustParse(DefaultKubeBinaryVersion).WithInfo(Get()) - return newEffectiveVersion(binaryVersion, false) -} - -// ValidateKubeEffectiveVersion validates the EmulationVersion is equal to the binary version at 1.31 for kube components. -// emulationVersion is introduced in 1.31, so it is only allowed to be equal to the binary version at 1.31. -func ValidateKubeEffectiveVersion(effectiveVersion EffectiveVersion) error { - binaryVersion := version.MajorMinor(effectiveVersion.BinaryVersion().Major(), effectiveVersion.BinaryVersion().Minor()) - if binaryVersion.EqualTo(version.MajorMinor(1, 31)) && !effectiveVersion.EmulationVersion().EqualTo(binaryVersion) { - return fmt.Errorf("emulation version needs to be equal to binary version(%s) in compatibility-version alpha, got %s", - binaryVersion.String(), effectiveVersion.EmulationVersion().String()) - } - return nil -} diff --git a/e2e/vendor/k8s.io/component-base/zpages/flagz/flagreader.go b/e2e/vendor/k8s.io/component-base/zpages/flagz/flagreader.go index 7e05928eb..40fe09b45 100644 --- a/e2e/vendor/k8s.io/component-base/zpages/flagz/flagreader.go +++ b/e2e/vendor/k8s.io/component-base/zpages/flagz/flagreader.go @@ -25,7 +25,7 @@ type Reader interface { GetFlagz() map[string]string } -// NamedFlagSetsGetter implements Reader for cliflag.NamedFlagSets +// NamedFlagSetsReader implements Reader for cliflag.NamedFlagSets type NamedFlagSetsReader struct { FlagSets cliflag.NamedFlagSets } diff --git a/e2e/vendor/k8s.io/component-base/zpages/flagz/flagz.go b/e2e/vendor/k8s.io/component-base/zpages/flagz/flagz.go index e6b52c30a..99a2f4482 100644 --- a/e2e/vendor/k8s.io/component-base/zpages/flagz/flagz.go +++ b/e2e/vendor/k8s.io/component-base/zpages/flagz/flagz.go @@ -23,15 +23,15 @@ import ( "math/rand" "net/http" "sort" - "strings" "sync" - "github.com/munnerz/goautoneg" - + "k8s.io/component-base/zpages/httputil" "k8s.io/klog/v2" ) const ( + DefaultFlagzPath = "/flagz" + flagzHeaderFmt = ` %s flags Warning: This endpoint is not meant to be machine parseable, has no formatting compatibility guarantees and is for debugging purposes only. @@ -40,8 +40,7 @@ Warning: This endpoint is not meant to be machine parseable, has no formatting c ) var ( - flagzSeparators = []string{":", ": ", "=", " "} - errUnsupportedMediaType = fmt.Errorf("media type not acceptable, must be: text/plain") + delimiters = []string{":", ": ", "=", " "} ) type registry struct { @@ -59,13 +58,13 @@ func Install(m mux, componentName string, flagReader Reader) { } func (reg *registry) installHandler(m mux, componentName string, flagReader Reader) { - m.Handle("/flagz", reg.handleFlags(componentName, flagReader)) + m.Handle(DefaultFlagzPath, reg.handleFlags(componentName, flagReader)) } func (reg *registry) handleFlags(componentName string, flagReader Reader) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if !acceptableMediaType(r) { - http.Error(w, errUnsupportedMediaType.Error(), http.StatusNotAcceptable) + if !httputil.AcceptableMediaType(r) { + http.Error(w, httputil.ErrUnsupportedMediaType.Error(), http.StatusNotAcceptable) return } @@ -76,8 +75,8 @@ func (reg *registry) handleFlags(componentName string, flagReader Reader) http.H return } - randomIndex := rand.Intn(len(flagzSeparators)) - separator := flagzSeparators[randomIndex] + randomIndex := rand.Intn(len(delimiters)) + separator := delimiters[randomIndex] // Randomize the delimiter for printing to prevent scraping of the response. printSortedFlags(®.response, flagReader.GetFlagz(), separator) }) @@ -90,29 +89,6 @@ func (reg *registry) handleFlags(componentName string, flagReader Reader) http.H } } -func acceptableMediaType(r *http.Request) bool { - accepts := goautoneg.ParseAccept(r.Header.Get("Accept")) - for _, accept := range accepts { - if !mediaTypeMatches(accept) { - continue - } - if len(accept.Params) == 0 { - return true - } - if len(accept.Params) == 1 { - if charset, ok := accept.Params["charset"]; ok && strings.EqualFold(charset, "utf-8") { - return true - } - } - } - return false -} - -func mediaTypeMatches(a goautoneg.Accept) bool { - return (a.Type == "text" || a.Type == "*") && - (a.SubType == "plain" || a.SubType == "*") -} - func printSortedFlags(w io.Writer, flags map[string]string, separator string) { var sortedKeys []string for key := range flags { diff --git a/e2e/vendor/k8s.io/component-base/zpages/httputil/httputil.go b/e2e/vendor/k8s.io/component-base/zpages/httputil/httputil.go new file mode 100644 index 000000000..da49474ba --- /dev/null +++ b/e2e/vendor/k8s.io/component-base/zpages/httputil/httputil.go @@ -0,0 +1,54 @@ +/* +Copyright 2024 The Kubernetes 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 httputil + +import ( + "fmt" + "net/http" + "strings" + + "github.com/munnerz/goautoneg" +) + +// ErrUnsupportedMediaType is the error returned when the request's +// Accept header does not contain "text/plain". +var ErrUnsupportedMediaType = fmt.Errorf("media type not acceptable, must be: text/plain") + +// AcceptableMediaType checks if the request's Accept header contains +// a supported media type with optional "charset=utf-8" parameter. +func AcceptableMediaType(r *http.Request) bool { + accepts := goautoneg.ParseAccept(r.Header.Get("Accept")) + for _, accept := range accepts { + if !mediaTypeMatches(accept) { + continue + } + if len(accept.Params) == 0 { + return true + } + if len(accept.Params) == 1 { + if charset, ok := accept.Params["charset"]; ok && strings.EqualFold(charset, "utf-8") { + return true + } + } + } + return false +} + +func mediaTypeMatches(a goautoneg.Accept) bool { + return (a.Type == "text" || a.Type == "*") && + (a.SubType == "plain" || a.SubType == "*") +} diff --git a/e2e/vendor/k8s.io/component-helpers/resource/helpers.go b/e2e/vendor/k8s.io/component-helpers/resource/helpers.go index 3bdcef6e8..780db5424 100644 --- a/e2e/vendor/k8s.io/component-helpers/resource/helpers.go +++ b/e2e/vendor/k8s.io/component-helpers/resource/helpers.go @@ -17,6 +17,8 @@ limitations under the License. package resource import ( + "strings" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" ) @@ -56,14 +58,14 @@ type PodResourcesOptions struct { var supportedPodLevelResources = sets.New(v1.ResourceCPU, v1.ResourceMemory) func SupportedPodLevelResources() sets.Set[v1.ResourceName] { - return supportedPodLevelResources + return supportedPodLevelResources.Clone().Insert(v1.ResourceHugePagesPrefix) } // IsSupportedPodLevelResources checks if a given resource is supported by pod-level // resource management through the PodLevelResources feature. Returns true if // the resource is supported. func IsSupportedPodLevelResource(name v1.ResourceName) bool { - return supportedPodLevelResources.Has(name) + return supportedPodLevelResources.Has(name) || strings.HasPrefix(string(name), v1.ResourceHugePagesPrefix) } // IsPodLevelResourcesSet check if PodLevelResources pod-level resources are set. @@ -144,10 +146,13 @@ func AggregateContainerRequests(pod *v1.Pod, opts PodResourcesOptions) v1.Resour reqs := reuseOrClearResourceList(opts.Reuse) var containerStatuses map[string]*v1.ContainerStatus if opts.UseStatusResources { - containerStatuses = make(map[string]*v1.ContainerStatus, len(pod.Status.ContainerStatuses)) + containerStatuses = make(map[string]*v1.ContainerStatus, len(pod.Status.ContainerStatuses)+len(pod.Status.InitContainerStatuses)) for i := range pod.Status.ContainerStatuses { containerStatuses[pod.Status.ContainerStatuses[i].Name] = &pod.Status.ContainerStatuses[i] } + for i := range pod.Status.InitContainerStatuses { + containerStatuses[pod.Status.InitContainerStatuses[i].Name] = &pod.Status.InitContainerStatuses[i] + } } for _, container := range pod.Spec.Containers { @@ -155,11 +160,7 @@ func AggregateContainerRequests(pod *v1.Pod, opts PodResourcesOptions) v1.Resour if opts.UseStatusResources { cs, found := containerStatuses[container.Name] if found && cs.Resources != nil { - if pod.Status.Resize == v1.PodResizeStatusInfeasible { - containerReqs = cs.Resources.Requests.DeepCopy() - } else { - containerReqs = max(container.Resources.Requests, cs.Resources.Requests) - } + containerReqs = determineContainerReqs(pod, &container, cs) } } @@ -177,7 +178,6 @@ func AggregateContainerRequests(pod *v1.Pod, opts PodResourcesOptions) v1.Resour restartableInitContainerReqs := v1.ResourceList{} initContainerReqs := v1.ResourceList{} // init containers define the minimum of any resource - // Note: In-place resize is not allowed for InitContainers, so no need to check for ResizeStatus value // // Let's say `InitContainerUse(i)` is the resource requirements when the i-th // init container is initializing, then @@ -186,6 +186,15 @@ func AggregateContainerRequests(pod *v1.Pod, opts PodResourcesOptions) v1.Resour // See https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/753-sidecar-containers#exposing-pod-resource-requirements for the detail. for _, container := range pod.Spec.InitContainers { containerReqs := container.Resources.Requests + if opts.UseStatusResources { + if container.RestartPolicy != nil && *container.RestartPolicy == v1.ContainerRestartPolicyAlways { + cs, found := containerStatuses[container.Name] + if found && cs.Resources != nil { + containerReqs = determineContainerReqs(pod, &container, cs) + } + } + } + if len(opts.NonMissingContainerRequests) > 0 { containerReqs = applyNonMissing(containerReqs, opts.NonMissingContainerRequests) } @@ -214,6 +223,42 @@ func AggregateContainerRequests(pod *v1.Pod, opts PodResourcesOptions) v1.Resour return reqs } +// determineContainerReqs will return a copy of the container requests based on if resizing is feasible or not. +func determineContainerReqs(pod *v1.Pod, container *v1.Container, cs *v1.ContainerStatus) v1.ResourceList { + if IsPodResizeInfeasible(pod) { + return max(cs.Resources.Requests, cs.AllocatedResources) + } + return max(container.Resources.Requests, cs.Resources.Requests, cs.AllocatedResources) +} + +// determineContainerLimits will return a copy of the container limits based on if resizing is feasible or not. +func determineContainerLimits(pod *v1.Pod, container *v1.Container, cs *v1.ContainerStatus) v1.ResourceList { + if IsPodResizeInfeasible(pod) { + return cs.Resources.Limits.DeepCopy() + } + return max(container.Resources.Limits, cs.Resources.Limits) +} + +// IsPodResizeInfeasible returns true if the pod condition PodResizePending is set to infeasible. +func IsPodResizeInfeasible(pod *v1.Pod) bool { + for _, condition := range pod.Status.Conditions { + if condition.Type == v1.PodResizePending { + return condition.Reason == v1.PodReasonInfeasible + } + } + return false +} + +// IsPodResizeDeferred returns true if the pod condition PodResizePending is set to deferred. +func IsPodResizeDeferred(pod *v1.Pod) bool { + for _, condition := range pod.Status.Conditions { + if condition.Type == v1.PodResizePending { + return condition.Reason == v1.PodReasonDeferred + } + } + return false +} + // applyNonMissing will return a copy of the given resource list with any missing values replaced by the nonMissing values func applyNonMissing(reqs v1.ResourceList, nonMissing v1.ResourceList) v1.ResourceList { cp := v1.ResourceList{} @@ -267,10 +312,13 @@ func AggregateContainerLimits(pod *v1.Pod, opts PodResourcesOptions) v1.Resource limits := reuseOrClearResourceList(opts.Reuse) var containerStatuses map[string]*v1.ContainerStatus if opts.UseStatusResources { - containerStatuses = make(map[string]*v1.ContainerStatus, len(pod.Status.ContainerStatuses)) + containerStatuses = make(map[string]*v1.ContainerStatus, len(pod.Status.ContainerStatuses)+len(pod.Status.InitContainerStatuses)) for i := range pod.Status.ContainerStatuses { containerStatuses[pod.Status.ContainerStatuses[i].Name] = &pod.Status.ContainerStatuses[i] } + for i := range pod.Status.InitContainerStatuses { + containerStatuses[pod.Status.InitContainerStatuses[i].Name] = &pod.Status.InitContainerStatuses[i] + } } for _, container := range pod.Spec.Containers { @@ -278,11 +326,7 @@ func AggregateContainerLimits(pod *v1.Pod, opts PodResourcesOptions) v1.Resource if opts.UseStatusResources { cs, found := containerStatuses[container.Name] if found && cs.Resources != nil { - if pod.Status.Resize == v1.PodResizeStatusInfeasible { - containerLimits = cs.Resources.Limits.DeepCopy() - } else { - containerLimits = max(container.Resources.Limits, cs.Resources.Limits) - } + containerLimits = determineContainerLimits(pod, &container, cs) } } @@ -303,6 +347,15 @@ func AggregateContainerLimits(pod *v1.Pod, opts PodResourcesOptions) v1.Resource // See https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/753-sidecar-containers#exposing-pod-resource-requirements for the detail. for _, container := range pod.Spec.InitContainers { containerLimits := container.Resources.Limits + if opts.UseStatusResources { + if container.RestartPolicy != nil && *container.RestartPolicy == v1.ContainerRestartPolicyAlways { + cs, found := containerStatuses[container.Name] + if found && cs.Resources != nil { + containerLimits = determineContainerLimits(pod, &container, cs) + } + } + } + // Is the init container marked as a restartable init container? if container.RestartPolicy != nil && *container.RestartPolicy == v1.ContainerRestartPolicyAlways { addResourceList(limits, containerLimits) @@ -348,23 +401,12 @@ func maxResourceList(list, newList v1.ResourceList) { } } -// max returns the result of max(a, b) for each named resource and is only used if we can't +// max returns the result of max(a, b...) for each named resource and is only used if we can't // accumulate into an existing resource list -func max(a v1.ResourceList, b v1.ResourceList) v1.ResourceList { - result := v1.ResourceList{} - for key, value := range a { - if other, found := b[key]; found { - if value.Cmp(other) <= 0 { - result[key] = other.DeepCopy() - continue - } - } - result[key] = value.DeepCopy() - } - for key, value := range b { - if _, found := result[key]; !found { - result[key] = value.DeepCopy() - } +func max(a v1.ResourceList, b ...v1.ResourceList) v1.ResourceList { + result := a.DeepCopy() + for _, other := range b { + maxResourceList(result, other) } return result } diff --git a/e2e/vendor/k8s.io/component-helpers/scheduling/corev1/doc.go b/e2e/vendor/k8s.io/component-helpers/scheduling/corev1/doc.go index c6cf8132a..98c82aadd 100644 --- a/e2e/vendor/k8s.io/component-helpers/scheduling/corev1/doc.go +++ b/e2e/vendor/k8s.io/component-helpers/scheduling/corev1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // - Be used by a core component and another kubernetes project (cluster-autoscaler, descheduler) // // And be a scheduling feature. -package corev1 // import "k8s.io/component-helpers/scheduling/corev1" +package corev1 diff --git a/e2e/vendor/k8s.io/controller-manager/config/doc.go b/e2e/vendor/k8s.io/controller-manager/config/doc.go index a98a0c8cd..164ec715b 100644 --- a/e2e/vendor/k8s.io/controller-manager/config/doc.go +++ b/e2e/vendor/k8s.io/controller-manager/config/doc.go @@ -16,4 +16,4 @@ limitations under the License. // +k8s:deepcopy-gen=package -package config // import "k8s.io/controller-manager/config" +package config diff --git a/e2e/vendor/k8s.io/controller-manager/config/v1/doc.go b/e2e/vendor/k8s.io/controller-manager/config/v1/doc.go index 037cfb785..2062f49b6 100644 --- a/e2e/vendor/k8s.io/controller-manager/config/v1/doc.go +++ b/e2e/vendor/k8s.io/controller-manager/config/v1/doc.go @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // +groupName=controllermanager.config.k8s.io -package v1 // import "k8s.io/controller-manager/config/v1" +package v1 diff --git a/e2e/vendor/k8s.io/controller-manager/config/v1alpha1/doc.go b/e2e/vendor/k8s.io/controller-manager/config/v1alpha1/doc.go index b01cf385d..72d1f3cf6 100644 --- a/e2e/vendor/k8s.io/controller-manager/config/v1alpha1/doc.go +++ b/e2e/vendor/k8s.io/controller-manager/config/v1alpha1/doc.go @@ -20,4 +20,4 @@ limitations under the License. // +k8s:openapi-gen=true // +groupName=controllermanager.config.k8s.io -package v1alpha1 // import "k8s.io/controller-manager/config/v1alpha1" +package v1alpha1 diff --git a/e2e/vendor/k8s.io/controller-manager/config/v1beta1/doc.go b/e2e/vendor/k8s.io/controller-manager/config/v1beta1/doc.go index 94cd3f128..0af8864a8 100644 --- a/e2e/vendor/k8s.io/controller-manager/config/v1beta1/doc.go +++ b/e2e/vendor/k8s.io/controller-manager/config/v1beta1/doc.go @@ -19,4 +19,4 @@ limitations under the License. // +k8s:openapi-gen=true // +groupName=controllermanager.config.k8s.io -package v1beta1 // import "k8s.io/controller-manager/config/v1beta1" +package v1beta1 diff --git a/e2e/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go b/e2e/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go index 08b6246ce..25e4fd09e 100644 --- a/e2e/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go +++ b/e2e/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go @@ -4,7 +4,7 @@ import ( "math/rand" "strings" - fuzz "github.com/google/gofuzz" + "sigs.k8s.io/randfill" "k8s.io/kube-openapi/pkg/validation/spec" ) @@ -25,15 +25,15 @@ func randAlphanumString() string { } var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ - func(s *string, c fuzz.Continue) { + func(s *string, c randfill.Continue) { // All OpenAPI V3 map keys must follow the corresponding // regex. Note that this restricts the range for all other // string values as well. str := randAlphanumString() *s = str }, - func(o *OpenAPI, c fuzz.Continue) { - c.FuzzNoCustom(o) + func(o *OpenAPI, c randfill.Continue) { + c.FillNoCustom(o) o.Version = "3.0.0" for i, val := range o.SecurityRequirement { if val == nil { @@ -48,45 +48,45 @@ var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ } }, - func(r *interface{}, c fuzz.Continue) { + func(r *interface{}, c randfill.Continue) { switch c.Intn(3) { case 0: *r = nil case 1: - n := c.RandString() + "x" + n := c.String(0) + "x" *r = n case 2: n := c.Float64() *r = n } }, - func(v **spec.Info, c fuzz.Continue) { + func(v **spec.Info, c randfill.Continue) { // Info is never nil *v = &spec.Info{} - c.FuzzNoCustom(*v) - (*v).Title = c.RandString() + "x" + c.FillNoCustom(*v) + (*v).Title = c.String(0) + "x" }, - func(v *Paths, c fuzz.Continue) { - c.Fuzz(&v.VendorExtensible) + func(v *Paths, c randfill.Continue) { + c.Fill(&v.VendorExtensible) num := c.Intn(5) if num > 0 { v.Paths = make(map[string]*Path) } for i := 0; i < num; i++ { val := Path{} - c.Fuzz(&val) - v.Paths["/"+c.RandString()] = &val + c.Fill(&val) + v.Paths["/"+c.String(0)] = &val } }, - func(v *SecurityScheme, c fuzz.Continue) { + func(v *SecurityScheme, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Refable) + c.Fill(&v.Refable) return } switch c.Intn(4) { case 0: v.Type = "apiKey" - v.Name = c.RandString() + "x" + v.Name = c.String(0) + "x" switch c.Intn(3) { case 0: v.In = "query" @@ -101,17 +101,17 @@ var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ v.Type = "oauth2" v.Flows = make(map[string]*OAuthFlow) flow := OAuthFlow{} - flow.AuthorizationUrl = c.RandString() + "x" + flow.AuthorizationUrl = c.String(0) + "x" v.Flows["implicit"] = &flow flow.Scopes = make(map[string]string) flow.Scopes["foo"] = "bar" case 3: v.Type = "openIdConnect" - v.OpenIdConnectUrl = "https://" + c.RandString() + v.OpenIdConnectUrl = "https://" + c.String(0) } v.Scheme = "basic" }, - func(v *spec.Ref, c fuzz.Continue) { + func(v *spec.Ref, c randfill.Continue) { switch c.Intn(7) { case 0: *v = spec.MustCreateRef("#/components/schemas/" + randAlphanumString()) @@ -127,13 +127,13 @@ var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ *v = spec.MustCreateRef("#/components/requestBodies/" + randAlphanumString()) } }, - func(v *Parameter, c fuzz.Continue) { + func(v *Parameter, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Refable) + c.Fill(&v.Refable) return } - c.Fuzz(&v.ParameterProps) - c.Fuzz(&v.VendorExtensible) + c.Fill(&v.ParameterProps) + c.Fill(&v.VendorExtensible) switch c.Intn(3) { case 0: @@ -145,44 +145,44 @@ var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ v.In = "cookie" } }, - func(v *RequestBody, c fuzz.Continue) { + func(v *RequestBody, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Refable) + c.Fill(&v.Refable) return } - c.Fuzz(&v.RequestBodyProps) - c.Fuzz(&v.VendorExtensible) + c.Fill(&v.RequestBodyProps) + c.Fill(&v.VendorExtensible) }, - func(v *Header, c fuzz.Continue) { + func(v *Header, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Refable) + c.Fill(&v.Refable) return } - c.Fuzz(&v.HeaderProps) - c.Fuzz(&v.VendorExtensible) + c.Fill(&v.HeaderProps) + c.Fill(&v.VendorExtensible) }, - func(v *ResponsesProps, c fuzz.Continue) { - c.Fuzz(&v.Default) + func(v *ResponsesProps, c randfill.Continue) { + c.Fill(&v.Default) n := c.Intn(5) for i := 0; i < n; i++ { r2 := Response{} - c.Fuzz(&r2) + c.Fill(&r2) // HTTP Status code in 100-599 Range code := c.Intn(500) + 100 v.StatusCodeResponses = make(map[int]*Response) v.StatusCodeResponses[code] = &r2 } }, - func(v *Response, c fuzz.Continue) { + func(v *Response, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Refable) + c.Fill(&v.Refable) return } - c.Fuzz(&v.ResponseProps) - c.Fuzz(&v.VendorExtensible) + c.Fill(&v.ResponseProps) + c.Fill(&v.VendorExtensible) }, - func(v *Operation, c fuzz.Continue) { - c.FuzzNoCustom(v) + func(v *Operation, c randfill.Continue) { + c.FillNoCustom(v) // Do not fuzz null values into the array. for i, val := range v.SecurityRequirement { if val == nil { @@ -196,85 +196,85 @@ var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ } } }, - func(v *spec.Extensions, c fuzz.Continue) { + func(v *spec.Extensions, c randfill.Continue) { numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { if *v == nil { *v = spec.Extensions{} } - (*v)["x-"+c.RandString()] = c.RandString() + (*v)["x-"+c.String(0)] = c.String(0) } }, - func(v *spec.ExternalDocumentation, c fuzz.Continue) { - c.Fuzz(&v.Description) + func(v *spec.ExternalDocumentation, c randfill.Continue) { + c.Fill(&v.Description) v.URL = "https://" + randAlphanumString() }, - func(v *spec.SchemaURL, c fuzz.Continue) { + func(v *spec.SchemaURL, c randfill.Continue) { *v = spec.SchemaURL("https://" + randAlphanumString()) }, - func(v *spec.SchemaOrBool, c fuzz.Continue) { + func(v *spec.SchemaOrBool, c randfill.Continue) { *v = spec.SchemaOrBool{} - if c.RandBool() { - v.Allows = c.RandBool() + if c.Bool() { + v.Allows = c.Bool() } else { v.Schema = &spec.Schema{} v.Allows = true - c.Fuzz(&v.Schema) + c.Fill(&v.Schema) } }, - func(v *spec.SchemaOrArray, c fuzz.Continue) { + func(v *spec.SchemaOrArray, c randfill.Continue) { *v = spec.SchemaOrArray{} - if c.RandBool() { + if c.Bool() { schema := spec.Schema{} - c.Fuzz(&schema) + c.Fill(&schema) v.Schema = &schema } else { v.Schemas = []spec.Schema{} numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { schema := spec.Schema{} - c.Fuzz(&schema) + c.Fill(&schema) v.Schemas = append(v.Schemas, schema) } } }, - func(v *spec.SchemaOrStringArray, c fuzz.Continue) { - if c.RandBool() { + func(v *spec.SchemaOrStringArray, c randfill.Continue) { + if c.Bool() { *v = spec.SchemaOrStringArray{} - if c.RandBool() { - c.Fuzz(&v.Property) + if c.Bool() { + c.Fill(&v.Property) } else { - c.Fuzz(&v.Schema) + c.Fill(&v.Schema) } } }, - func(v *spec.Schema, c fuzz.Continue) { + func(v *spec.Schema, c randfill.Continue) { if c.Intn(refChance) == 0 { - c.Fuzz(&v.Ref) + c.Fill(&v.Ref) return } - if c.RandBool() { + if c.Bool() { // file schema - c.Fuzz(&v.Default) - c.Fuzz(&v.Description) - c.Fuzz(&v.Example) - c.Fuzz(&v.ExternalDocs) + c.Fill(&v.Default) + c.Fill(&v.Description) + c.Fill(&v.Example) + c.Fill(&v.ExternalDocs) - c.Fuzz(&v.Format) - c.Fuzz(&v.ReadOnly) - c.Fuzz(&v.Required) - c.Fuzz(&v.Title) + c.Fill(&v.Format) + c.Fill(&v.ReadOnly) + c.Fill(&v.Required) + c.Fill(&v.Title) v.Type = spec.StringOrArray{"file"} } else { // normal schema - c.Fuzz(&v.SchemaProps) - c.Fuzz(&v.SwaggerSchemaProps) - c.Fuzz(&v.VendorExtensible) - c.Fuzz(&v.ExtraProps) + c.Fill(&v.SchemaProps) + c.Fill(&v.SwaggerSchemaProps) + c.Fill(&v.VendorExtensible) + c.Fill(&v.ExtraProps) } }, diff --git a/e2e/vendor/k8s.io/pod-security-admission/api/doc.go b/e2e/vendor/k8s.io/pod-security-admission/api/doc.go index a35374be3..a03c924a4 100644 --- a/e2e/vendor/k8s.io/pod-security-admission/api/doc.go +++ b/e2e/vendor/k8s.io/pod-security-admission/api/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package api contains constants and helpers for PodSecurity admission label keys and values -package api // import "k8s.io/pod-security-admission/api" +package api diff --git a/e2e/vendor/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go b/e2e/vendor/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go index e171cdd60..06ae4890c 100644 --- a/e2e/vendor/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go +++ b/e2e/vendor/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go @@ -36,6 +36,7 @@ limits usage of inline pod volume sources to: * csi * persistentVolumeClaim * ephemeral +* image **Restricted Fields:** @@ -95,6 +96,7 @@ func restrictedVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSp volume.DownwardAPI != nil, volume.EmptyDir != nil, volume.Ephemeral != nil, + volume.Image != nil, volume.PersistentVolumeClaim != nil, volume.Projected != nil, volume.Secret != nil: diff --git a/e2e/vendor/k8s.io/pod-security-admission/policy/doc.go b/e2e/vendor/k8s.io/pod-security-admission/policy/doc.go index a6211eb5d..f8c583101 100644 --- a/e2e/vendor/k8s.io/pod-security-admission/policy/doc.go +++ b/e2e/vendor/k8s.io/pod-security-admission/policy/doc.go @@ -15,4 +15,4 @@ limitations under the License. */ // Package policy contains implementations of Pod Security Standards checks -package policy // import "k8s.io/pod-security-admission/policy" +package policy diff --git a/e2e/vendor/modules.txt b/e2e/vendor/modules.txt index 463abadaf..1f19e2c27 100644 --- a/e2e/vendor/modules.txt +++ b/e2e/vendor/modules.txt @@ -1,4 +1,4 @@ -# cel.dev/expr v0.19.1 +# cel.dev/expr v0.20.0 ## explicit; go 1.21.1 cel.dev/expr # github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab @@ -17,9 +17,6 @@ github.com/NYTimes/gziphandler # github.com/antlr4-go/antlr/v4 v4.13.0 ## explicit; go 1.20 github.com/antlr4-go/antlr/v4 -# github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a -## explicit -github.com/asaskevich/govalidator # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 github.com/beorn7/perks/quantile @@ -167,7 +164,7 @@ github.com/google/cadvisor/utils/sysfs github.com/google/cadvisor/utils/sysinfo github.com/google/cadvisor/version github.com/google/cadvisor/watcher -# github.com/google/cel-go v0.22.0 +# github.com/google/cel-go v0.23.2 ## explicit; go 1.21.1 github.com/google/cel-go/cel github.com/google/cel-go/checker @@ -206,24 +203,20 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/gofuzz v1.2.0 -## explicit; go 1.12 -github.com/google/gofuzz -github.com/google/gofuzz/bytesource # github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 ## explicit; go 1.23 github.com/google/pprof/profile # github.com/google/uuid v1.6.0 ## explicit github.com/google/uuid -# github.com/gorilla/websocket v1.5.0 -## explicit; go 1.12 +# github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 +## explicit; go 1.20 github.com/gorilla/websocket # github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 ## explicit github.com/grpc-ecosystem/go-grpc-prometheus -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 -## explicit; go 1.20 +# github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 +## explicit; go 1.22.7 github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities @@ -380,24 +373,24 @@ github.com/stoewer/go-strcase # github.com/x448/float16 v0.8.4 ## explicit; go 1.11 github.com/x448/float16 -# go.etcd.io/etcd/api/v3 v3.5.16 -## explicit; go 1.22 +# go.etcd.io/etcd/api/v3 v3.5.21 +## explicit; go 1.23.0 go.etcd.io/etcd/api/v3/authpb go.etcd.io/etcd/api/v3/etcdserverpb go.etcd.io/etcd/api/v3/membershippb go.etcd.io/etcd/api/v3/mvccpb go.etcd.io/etcd/api/v3/v3rpc/rpctypes go.etcd.io/etcd/api/v3/version -# go.etcd.io/etcd/client/pkg/v3 v3.5.16 -## explicit; go 1.22 +# go.etcd.io/etcd/client/pkg/v3 v3.5.21 +## explicit; go 1.23.0 go.etcd.io/etcd/client/pkg/v3/fileutil go.etcd.io/etcd/client/pkg/v3/logutil go.etcd.io/etcd/client/pkg/v3/systemd go.etcd.io/etcd/client/pkg/v3/tlsutil go.etcd.io/etcd/client/pkg/v3/transport go.etcd.io/etcd/client/pkg/v3/types -# go.etcd.io/etcd/client/v3 v3.5.16 -## explicit; go 1.22 +# go.etcd.io/etcd/client/v3 v3.5.21 +## explicit; go 1.23.0 go.etcd.io/etcd/client/v3 go.etcd.io/etcd/client/v3/credentials go.etcd.io/etcd/client/v3/internal/endpoint @@ -411,9 +404,10 @@ go.opentelemetry.io/auto/sdk/internal/telemetry ## explicit; go 1.22.7 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 -## explicit; go 1.21 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 +## explicit; go 1.22.0 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconvutil # go.opentelemetry.io/otel v1.34.0 @@ -431,14 +425,13 @@ go.opentelemetry.io/otel/semconv/internal go.opentelemetry.io/otel/semconv/v1.12.0 go.opentelemetry.io/otel/semconv/v1.17.0 go.opentelemetry.io/otel/semconv/v1.20.0 -go.opentelemetry.io/otel/semconv/v1.24.0 go.opentelemetry.io/otel/semconv/v1.26.0 -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 -## explicit; go 1.21 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 +## explicit; go 1.22.7 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.27.0 -## explicit; go 1.21 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 +## explicit; go 1.22.7 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/envconfig @@ -462,8 +455,8 @@ go.opentelemetry.io/otel/sdk/trace go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.3.1 -## explicit; go 1.17 +# go.opentelemetry.io/proto/otlp v1.4.0 +## explicit; go 1.22.7 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/resource/v1 @@ -570,7 +563,7 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/time v0.8.0 +# golang.org/x/time v0.9.0 ## explicit; go 1.18 golang.org/x/time/rate # golang.org/x/tools v0.31.0 @@ -578,18 +571,18 @@ golang.org/x/time/rate golang.org/x/tools/cover golang.org/x/tools/go/ast/inspector golang.org/x/tools/internal/astutil/edge -# google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 +# google.golang.org/genproto/googleapis/api v0.0.0-20250218202821-56aae31c358a ## explicit; go 1.22 google.golang.org/genproto/googleapis/api google.golang.org/genproto/googleapis/api/annotations google.golang.org/genproto/googleapis/api/expr/v1alpha1 google.golang.org/genproto/googleapis/api/httpbody -# google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f +# google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a ## explicit; go 1.22 google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.71.1 -## explicit; go 1.22.0 +# google.golang.org/grpc v1.72.0 +## explicit; go 1.23 google.golang.org/grpc google.golang.org/grpc/attributes google.golang.org/grpc/backoff @@ -710,7 +703,7 @@ gopkg.in/natefinch/lumberjack.v2 # gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 -# k8s.io/api v0.32.3 => k8s.io/api v0.32.2 +# k8s.io/api v0.33.0 => k8s.io/api v0.32.2 ## explicit; go 1.23.0 k8s.io/api/admission/v1 k8s.io/api/admission/v1beta1 @@ -776,15 +769,17 @@ k8s.io/api/storagemigration/v1alpha1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/features -# k8s.io/apimachinery v0.32.3 -## explicit; go 1.23.0 +# k8s.io/apimachinery v0.33.0 +## explicit; go 1.24.0 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors k8s.io/apimachinery/pkg/api/meta k8s.io/apimachinery/pkg/api/meta/testrestmapper +k8s.io/apimachinery/pkg/api/operation k8s.io/apimachinery/pkg/api/resource k8s.io/apimachinery/pkg/api/validation k8s.io/apimachinery/pkg/api/validation/path +k8s.io/apimachinery/pkg/apis/asn1 k8s.io/apimachinery/pkg/apis/meta/internalversion k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme k8s.io/apimachinery/pkg/apis/meta/internalversion/validation @@ -844,8 +839,8 @@ k8s.io/apimachinery/pkg/watch k8s.io/apimachinery/third_party/forked/golang/json k8s.io/apimachinery/third_party/forked/golang/netutil k8s.io/apimachinery/third_party/forked/golang/reflect -# k8s.io/apiserver v0.32.3 -## explicit; go 1.23.0 +# k8s.io/apiserver v0.33.0 +## explicit; go 1.24.0 k8s.io/apiserver/pkg/admission k8s.io/apiserver/pkg/admission/configuration k8s.io/apiserver/pkg/admission/initializer @@ -957,7 +952,9 @@ k8s.io/apiserver/pkg/server/routine k8s.io/apiserver/pkg/server/storage k8s.io/apiserver/pkg/storage k8s.io/apiserver/pkg/storage/cacher +k8s.io/apiserver/pkg/storage/cacher/delegator k8s.io/apiserver/pkg/storage/cacher/metrics +k8s.io/apiserver/pkg/storage/cacher/progress k8s.io/apiserver/pkg/storage/errors k8s.io/apiserver/pkg/storage/etcd3 k8s.io/apiserver/pkg/storage/etcd3/metrics @@ -975,6 +972,7 @@ k8s.io/apiserver/pkg/storage/value/encrypt/identity k8s.io/apiserver/pkg/storage/value/encrypt/secretbox k8s.io/apiserver/pkg/storageversion k8s.io/apiserver/pkg/util/apihelpers +k8s.io/apiserver/pkg/util/compatibility k8s.io/apiserver/pkg/util/dryrun k8s.io/apiserver/pkg/util/feature k8s.io/apiserver/pkg/util/flowcontrol @@ -991,6 +989,7 @@ k8s.io/apiserver/pkg/util/peerproxy/metrics k8s.io/apiserver/pkg/util/shufflesharding k8s.io/apiserver/pkg/util/webhook k8s.io/apiserver/pkg/util/x509metrics +k8s.io/apiserver/pkg/validation k8s.io/apiserver/pkg/warning k8s.io/apiserver/plugin/pkg/audit/buffered k8s.io/apiserver/plugin/pkg/audit/log @@ -1347,8 +1346,8 @@ k8s.io/client-go/util/keyutil k8s.io/client-go/util/retry k8s.io/client-go/util/watchlist k8s.io/client-go/util/workqueue -# k8s.io/cloud-provider v0.32.3 -## explicit; go 1.23.0 +# k8s.io/cloud-provider v0.33.0 +## explicit; go 1.24.0 k8s.io/cloud-provider k8s.io/cloud-provider/app/config k8s.io/cloud-provider/config @@ -1362,9 +1361,10 @@ k8s.io/cloud-provider/names k8s.io/cloud-provider/options k8s.io/cloud-provider/volume k8s.io/cloud-provider/volume/helpers -# k8s.io/component-base v0.32.3 -## explicit; go 1.23.0 +# k8s.io/component-base v0.33.0 +## explicit; go 1.24.0 k8s.io/component-base/cli/flag +k8s.io/component-base/compatibility k8s.io/component-base/config k8s.io/component-base/config/options k8s.io/component-base/config/v1alpha1 @@ -1389,8 +1389,9 @@ k8s.io/component-base/tracing/api/v1 k8s.io/component-base/version k8s.io/component-base/zpages/features k8s.io/component-base/zpages/flagz -# k8s.io/component-helpers v0.32.3 -## explicit; go 1.23.0 +k8s.io/component-base/zpages/httputil +# k8s.io/component-helpers v0.33.0 +## explicit; go 1.24.0 k8s.io/component-helpers/node/topology k8s.io/component-helpers/node/util/sysctl k8s.io/component-helpers/resource @@ -1398,8 +1399,8 @@ k8s.io/component-helpers/scheduling/corev1 k8s.io/component-helpers/scheduling/corev1/nodeaffinity k8s.io/component-helpers/storage/ephemeral k8s.io/component-helpers/storage/volume -# k8s.io/controller-manager v0.32.3 -## explicit; go 1.23.0 +# k8s.io/controller-manager v0.33.0 +## explicit; go 1.24.0 k8s.io/controller-manager/config k8s.io/controller-manager/config/v1 k8s.io/controller-manager/config/v1alpha1 @@ -1441,13 +1442,13 @@ k8s.io/klog/v2/internal/severity k8s.io/klog/v2/internal/sloghandler k8s.io/klog/v2/internal/verbosity k8s.io/klog/v2/textlogger -# k8s.io/kms v0.32.3 -## explicit; go 1.23.0 +# k8s.io/kms v0.33.0 +## explicit; go 1.24.0 k8s.io/kms/apis/v1beta1 k8s.io/kms/apis/v2 k8s.io/kms/pkg/service k8s.io/kms/pkg/util -# k8s.io/kube-openapi v0.0.0-20241212222426-2c72e554b1e7 +# k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff ## explicit; go 1.21 k8s.io/kube-openapi/pkg/builder k8s.io/kube-openapi/pkg/builder3 @@ -1649,8 +1650,8 @@ k8s.io/kubernetes/third_party/forked/libcontainer/utils # k8s.io/mount-utils v0.32.2 ## explicit; go 1.23.0 k8s.io/mount-utils -# k8s.io/pod-security-admission v0.32.3 -## explicit; go 1.23.0 +# k8s.io/pod-security-admission v0.33.0 +## explicit; go 1.24.0 k8s.io/pod-security-admission/api k8s.io/pod-security-admission/policy # k8s.io/utils v0.0.0-20241210054802-24370beab758 @@ -1674,7 +1675,7 @@ k8s.io/utils/pointer k8s.io/utils/ptr k8s.io/utils/strings k8s.io/utils/trace -# sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.0 +# sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 ## explicit; go 1.21 sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics @@ -1684,7 +1685,11 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client ## explicit; go 1.23 sigs.k8s.io/json sigs.k8s.io/json/internal/golang/encoding/json -# sigs.k8s.io/structured-merge-diff/v4 v4.5.0 +# sigs.k8s.io/randfill v1.0.0 +## explicit; go 1.18 +sigs.k8s.io/randfill +sigs.k8s.io/randfill/bytesource +# sigs.k8s.io/structured-merge-diff/v4 v4.6.0 ## explicit; go 1.13 sigs.k8s.io/structured-merge-diff/v4/fieldpath sigs.k8s.io/structured-merge-diff/v4/merge diff --git a/e2e/vendor/sigs.k8s.io/randfill/CONTRIBUTING.md b/e2e/vendor/sigs.k8s.io/randfill/CONTRIBUTING.md new file mode 100644 index 000000000..7566c879c --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/CONTRIBUTING.md @@ -0,0 +1,43 @@ +# Contributing Guidelines + +Welcome to Kubernetes. We are excited about the prospect of you joining our [community](https://git.k8s.io/community)! The Kubernetes community abides by the CNCF [code of conduct](code-of-conduct.md). Here is an excerpt: + +_As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities._ + +## Getting Started + +We have full documentation on how to get started contributing here: + + + +- [Contributor License Agreement](https://git.k8s.io/community/CLA.md) Kubernetes projects require that you sign a Contributor License Agreement (CLA) before we can accept your pull requests +- [Kubernetes Contributor Guide](https://git.k8s.io/community/contributors/guide) - Main contributor documentation, or you can just jump directly to the [contributing section](https://git.k8s.io/community/contributors/guide#contributing) +- [Contributor Cheat Sheet](https://git.k8s.io/community/contributors/guide/contributor-cheatsheet) - Common resources for existing developers + +## Mentorship + +- [Mentoring Initiatives](https://git.k8s.io/community/mentoring) - We have a diverse set of mentorship programs available that are always looking for volunteers! + + + +## Project Management + +The [maintainers](https://github.com/kubernetes-sigs/randfill/blob/main/OWNERS_ALIASES#L12) of this project (and often others who have official positions on the [contributor ladder](https://github.com/kubernetes-sigs/randfill/blob/main/OWNERS_ALIASES)) are responsible for performing project management which oversees development and maintenance of the API, tests, tools, e.t.c. While we try to be generally flexible when it comes to the management of individual pieces (such as Issues or PRs), we have some rules and guidelines which help us plan, coordinate and reduce waste. In this section you'll find some rules/guidelines for contributors related to project management which may extend or go beyond what you would find in the standard [Kubernetes Contributor Guide](https://git.k8s.io/community/contributors/guide). + +### Bumping stale and closed Issues & PRs + +Maintainers are ultimately responsible for triaging new issues and PRs, accepting or declining them, deciding priority and fitting them into milestones intended for future releases. Bots are responsible for marking issues and PRs which stagnate as stale, or closing them if progress does not continue for a long period of time. Due to the nature of this community-driven development effort (we do not have dedicated engineering resources, we rely on the community which is effectively "volunteer time") **not all issues can be accepted, prioritized or completed**. + +You may find times when an issue you're subscribed to and interested in seems to stagnate, or perhaps gets auto-closed. Prior to bumping or directly re-opening issues yourself, we generally ask that you bring these up for discussion on the agenda for one of our community syncs if possible, or bring them up for discussion in Slack or the mailing list as this gives us a better opportunity to discuss the issue and determine viability and logistics. If feasible we **highly recommend being ready to contribute directly** to any stale or unprioritized effort that you want to see move forward, as **the best way to ensure progress is to engage with the community and personally invest time**. + +We (the community) aren't opposed to making exceptions in some cases, but when in doubt please follow the above guidelines before bumping closed or stale issues if you're not ready to personally invest time in them. We are responsible for managing these and without further context or engagement we may set these back to how they were previously organized. diff --git a/e2e/vendor/github.com/google/gofuzz/LICENSE b/e2e/vendor/sigs.k8s.io/randfill/LICENSE similarity index 99% rename from e2e/vendor/github.com/google/gofuzz/LICENSE rename to e2e/vendor/sigs.k8s.io/randfill/LICENSE index d64569567..9dd29274c 100644 --- a/e2e/vendor/github.com/google/gofuzz/LICENSE +++ b/e2e/vendor/sigs.k8s.io/randfill/LICENSE @@ -1,4 +1,3 @@ - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -179,7 +178,7 @@ APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" + boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -187,7 +186,8 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2014 The gofuzz Authors + Copyright 2025 The Kubernetes Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/e2e/vendor/sigs.k8s.io/randfill/NOTICE b/e2e/vendor/sigs.k8s.io/randfill/NOTICE new file mode 100644 index 000000000..6984e71f6 --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/NOTICE @@ -0,0 +1,24 @@ +When donating the randfill project to the CNCF, we could not reach all the +gofuzz contributors to sign the CNCF CLA. As such, according to the CNCF rules +to donate a repository, we must add a NOTICE referencing section 7 of the CLA +with a list of developers who could not be reached. + +`7. Should You wish to submit work that is not Your original creation, You may +submit it to the Foundation separately from any Contribution, identifying the +complete details of its source and of any license or other restriction +(including, but not limited to, related patents, trademarks, and license +agreements) of which you are personally aware, and conspicuously marking the +work as "Submitted on behalf of a third-party: [named here]".` + +Submitted on behalf of a third-party: @dnephin (Daniel Nephin) +Submitted on behalf of a third-party: @AlekSi (Alexey Palazhchenko) +Submitted on behalf of a third-party: @bbigras (Bruno Bigras) +Submitted on behalf of a third-party: @samirkut (Samir) +Submitted on behalf of a third-party: @posener (Eyal Posener) +Submitted on behalf of a third-party: @Ashikpaul (Ashik Paul) +Submitted on behalf of a third-party: @kwongtailau (Kwongtai) +Submitted on behalf of a third-party: @ericcornelissen (Eric Cornelissen) +Submitted on behalf of a third-party: @eclipseo (Robert-André Mauchin) +Submitted on behalf of a third-party: @yanzhoupan (Andrew Pan) +Submitted on behalf of a third-party: @STRRL (Zhiqiang ZHOU) +Submitted on behalf of a third-party: @disconnect3d (Disconnect3d) diff --git a/e2e/vendor/sigs.k8s.io/randfill/OWNERS b/e2e/vendor/sigs.k8s.io/randfill/OWNERS new file mode 100644 index 000000000..59f6a50f6 --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/OWNERS @@ -0,0 +1,8 @@ +# See the OWNERS docs at https://go.k8s.io/owners +# See the OWNERS_ALIASES file at https://github.com/kubernetes-sigs/randfill/blob/main/OWNERS_ALIASES for a list of members for each alias. + +approvers: + - sig-testing-leads + - thockin + +reviewers: [] diff --git a/e2e/vendor/sigs.k8s.io/randfill/OWNERS_ALIASES b/e2e/vendor/sigs.k8s.io/randfill/OWNERS_ALIASES new file mode 100644 index 000000000..927f1209b --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/OWNERS_ALIASES @@ -0,0 +1,14 @@ +# See the OWNERS docs: https://git.k8s.io/community/contributors/guide/owners.md +# This file should be kept in sync with k/org. + +aliases: + # Reference: https://github.com/kubernetes/org/blob/main/OWNERS_ALIASES + sig-testing-leads: + - BenTheElder + - alvaroaleman + - aojea + - cjwagner + - jbpratt + - michelle192837 + - pohly + - xmcqueen diff --git a/e2e/vendor/github.com/google/gofuzz/README.md b/e2e/vendor/sigs.k8s.io/randfill/README.md similarity index 53% rename from e2e/vendor/github.com/google/gofuzz/README.md rename to e2e/vendor/sigs.k8s.io/randfill/README.md index b503aae7d..d892fc9f5 100644 --- a/e2e/vendor/github.com/google/gofuzz/README.md +++ b/e2e/vendor/sigs.k8s.io/randfill/README.md @@ -1,39 +1,46 @@ -gofuzz +randfill ====== -gofuzz is a library for populating go objects with random values. +randfill is a library for populating go objects with random values. -[![GoDoc](https://godoc.org/github.com/google/gofuzz?status.svg)](https://godoc.org/github.com/google/gofuzz) -[![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz) +This is a fork of github.com/google/gofuzz, which was archived. + +NOTE: This repo is supported only for use within Kubernetes. It is not our +intention to support general use. That said, if it works for you, that's +great! If you have a problem, please feel free to file an issue, but be aware +that it may not be a priority for us to fix it unless it is affecting +Kubernetes. PRs are welcome, within reason. + +[![GoDoc](https://godoc.org/sigs.k8s.io/randfill?status.svg)](https://godoc.org/sigs.k8s.io/randfill) This is useful for testing: * Do your project's objects really serialize/unserialize correctly in all cases? * Is there an incorrectly formatted object that will cause your project to panic? -Import with ```import "github.com/google/gofuzz"``` +Import with ```import "sigs.k8s.io/randfill"``` You can use it on single variables: ```go -f := fuzz.New() +f := randfill.New() var myInt int -f.Fuzz(&myInt) // myInt gets a random value. +f.Fill(&myInt) // myInt gets a random value. ``` You can use it on maps: ```go -f := fuzz.New().NilChance(0).NumElements(1, 1) +f := randfill.New().NilChance(0).NumElements(1, 1) var myMap map[ComplexKeyType]string -f.Fuzz(&myMap) // myMap will have exactly one element. +f.Fill(&myMap) // myMap will have exactly one element. ``` Customize the chance of getting a nil pointer: ```go -f := fuzz.New().NilChance(.5) +f := randfill.New().NilChance(.5) var fancyStruct struct { A, B, C, D *string } -f.Fuzz(&fancyStruct) // About half the pointers should be set. +f.Fill(&fancyStruct) // About half the pointers should be set. ``` You can even customize the randomization completely if needed: @@ -49,25 +56,27 @@ type MyInfo struct { BInfo *string } -f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { +f := randfill.New().NilChance(0).Funcs( + func(e *MyInfo, c randfill.Continue) { switch c.Intn(2) { case 0: e.Type = A - c.Fuzz(&e.AInfo) + c.Fill(&e.AInfo) case 1: e.Type = B - c.Fuzz(&e.BInfo) + c.Fill(&e.BInfo) } }, ) var myObject MyInfo -f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. +f.Fill(&myObject) // Type will correspond to whether A or B info is set. ``` See more examples in ```example_test.go```. +## dvyukov/go-fuzz integration + You can use this library for easier [go-fuzz](https://github.com/dvyukov/go-fuzz)ing. go-fuzz provides the user a byte-slice, which should be converted to different inputs for the tested function. This library can help convert the byte slice. Consider for @@ -76,11 +85,11 @@ example a fuzz test for a the function `mypackage.MyFunc` that takes an int argu // +build gofuzz package mypackage -import fuzz "github.com/google/gofuzz" +import "sigs.k8s.io/randfill" func Fuzz(data []byte) int { var i int - fuzz.NewFromGoFuzz(data).Fuzz(&i) + randfill.NewFromGoFuzz(data).Fill(&i) MyFunc(i) return 0 } diff --git a/e2e/vendor/sigs.k8s.io/randfill/SECURITY_CONTACTS b/e2e/vendor/sigs.k8s.io/randfill/SECURITY_CONTACTS new file mode 100644 index 000000000..91d785337 --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/SECURITY_CONTACTS @@ -0,0 +1,16 @@ +# Defined below are the security contacts for this repo. +# +# They are the contact point for the Product Security Committee to reach out +# to for triaging and handling of incoming issues. +# +# The below names agree to abide by the +# [Embargo Policy](https://git.k8s.io/security/private-distributors-list.md#embargo-policy) +# and will be removed and replaced if they violate that agreement. +# +# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE +# INSTRUCTIONS AT https://kubernetes.io/security/ + +thockin +BenTheElder +aojea +pohly diff --git a/e2e/vendor/github.com/google/gofuzz/bytesource/bytesource.go b/e2e/vendor/sigs.k8s.io/randfill/bytesource/bytesource.go similarity index 100% rename from e2e/vendor/github.com/google/gofuzz/bytesource/bytesource.go rename to e2e/vendor/sigs.k8s.io/randfill/bytesource/bytesource.go diff --git a/e2e/vendor/sigs.k8s.io/randfill/code-of-conduct.md b/e2e/vendor/sigs.k8s.io/randfill/code-of-conduct.md new file mode 100644 index 000000000..0d15c00cf --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/code-of-conduct.md @@ -0,0 +1,3 @@ +# Kubernetes Community Code of Conduct + +Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md) diff --git a/e2e/vendor/sigs.k8s.io/randfill/randfill.go b/e2e/vendor/sigs.k8s.io/randfill/randfill.go new file mode 100644 index 000000000..b73482484 --- /dev/null +++ b/e2e/vendor/sigs.k8s.io/randfill/randfill.go @@ -0,0 +1,682 @@ +/* +Copyright 2014 Google Inc. All rights reserved. +Copyright 2014 The gofuzz Authors. +Copyright 2025 The Kubernetes 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 randfill is a library for populating go objects with random values. +package randfill + +import ( + "fmt" + "math/rand" + "reflect" + "regexp" + "sync" + "time" + "unsafe" + + "strings" + + "sigs.k8s.io/randfill/bytesource" +) + +// funcMap is a map from a type to a function that randfills that type. The +// function is a reflect.Value because the type being filled is different for +// each func. +type funcMap map[reflect.Type]reflect.Value + +// Filler knows how to fill any object with random fields. +type Filler struct { + customFuncs funcMap + defaultFuncs funcMap + r *rand.Rand + nilChance float64 + minElements int + maxElements int + maxDepth int + allowUnexportedFields bool + skipFieldPatterns []*regexp.Regexp + + lock sync.Mutex +} + +// New returns a new Filler. Customize your Filler further by calling Funcs, +// RandSource, NilChance, or NumElements in any order. +func New() *Filler { + return NewWithSeed(time.Now().UnixNano()) +} + +func NewWithSeed(seed int64) *Filler { + f := &Filler{ + defaultFuncs: funcMap{ + reflect.TypeOf(&time.Time{}): reflect.ValueOf(randfillTime), + }, + + customFuncs: funcMap{}, + r: rand.New(rand.NewSource(seed)), + nilChance: .2, + minElements: 1, + maxElements: 10, + maxDepth: 100, + allowUnexportedFields: false, + } + return f +} + +// NewFromGoFuzz is a helper function that enables using randfill (this +// project) with go-fuzz (https://github.com/dvyukov/go-fuzz) for continuous +// fuzzing. Essentially, it enables translating the fuzzing bytes from +// go-fuzz to any Go object using this library. +// +// This implementation promises a constant translation from a given slice of +// bytes to the fuzzed objects. This promise will remain over future +// versions of Go and of this library. +// +// Note: the returned Filler should not be shared between multiple goroutines, +// as its deterministic output will no longer be available. +// +// Example: use go-fuzz to test the function `MyFunc(int)` in the package +// `mypackage`. Add the file: "mypackage_fuzz.go" with the content: +// +// // +build gofuzz +// package mypackage +// import "sigs.k8s.io/randfill" +// +// func Fuzz(data []byte) int { +// var i int +// randfill.NewFromGoFuzz(data).Fill(&i) +// MyFunc(i) +// return 0 +// } +func NewFromGoFuzz(data []byte) *Filler { + return New().RandSource(bytesource.New(data)) +} + +// Funcs registers custom fill functions for this Filler. +// +// Each entry in customFuncs must be a function taking two parameters. +// The first parameter must be a pointer or map. It is the variable that +// function will fill with random data. The second parameter must be a +// randfill.Continue, which will provide a source of randomness and a way +// to automatically continue filling smaller pieces of the first parameter. +// +// These functions are called sensibly, e.g., if you wanted custom string +// filling, the function `func(s *string, c randfill.Continue)` would get +// called and passed the address of strings. Maps and pointers will always +// be made/new'd for you, ignoring the NilChance option. For slices, it +// doesn't make much sense to pre-create them--Filler doesn't know how +// long you want your slice--so take a pointer to a slice, and make it +// yourself. (If you don't want your map/pointer type pre-made, take a +// pointer to it, and make it yourself.) See the examples for a range of +// custom functions. +// +// If a function is already registered for a type, and a new function is +// provided, the previous function will be replaced with the new one. +func (f *Filler) Funcs(customFuncs ...interface{}) *Filler { + for i := range customFuncs { + v := reflect.ValueOf(customFuncs[i]) + if v.Kind() != reflect.Func { + panic("Filler.Funcs: all arguments must be functions") + } + t := v.Type() + if t.NumIn() != 2 || t.NumOut() != 0 { + panic("Filler.Funcs: all customFuncs must have 2 arguments and 0 returns") + } + argT := t.In(0) + switch argT.Kind() { + case reflect.Ptr, reflect.Map: + default: + panic("Filler.Funcs: customFuncs' first argument must be a pointer or map type") + } + if t.In(1) != reflect.TypeOf(Continue{}) { + panic("Filler.Funcs: customFuncs' second argument must be a randfill.Continue") + } + f.customFuncs[argT] = v + } + return f +} + +// RandSource causes this Filler to get values from the given source of +// randomness. Use this if you want deterministic filling. +func (f *Filler) RandSource(s rand.Source) *Filler { + f.r = rand.New(s) + return f +} + +// NilChance sets the probability of creating a nil pointer, map, or slice to +// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. +func (f *Filler) NilChance(p float64) *Filler { + if p < 0 || p > 1 { + panic("Filler.NilChance: p must be between 0 and 1, inclusive") + } + f.nilChance = p + return f +} + +// NumElements sets the minimum and maximum number of elements that will be +// added to a non-nil map or slice. +func (f *Filler) NumElements(min, max int) *Filler { + if min < 0 { + panic("Filler.NumElements: min must be >= 0") + } + if min > max { + panic("Filler.NumElements: min must be <= max") + } + f.minElements = min + f.maxElements = max + return f +} + +func (f *Filler) genElementCount() int { + if f.minElements == f.maxElements { + return f.minElements + } + return f.minElements + f.r.Intn(f.maxElements-f.minElements+1) +} + +func (f *Filler) genShouldFill() bool { + return f.r.Float64() >= f.nilChance +} + +// MaxDepth sets the maximum number of recursive fill calls that will be made +// before stopping. This includes struct members, pointers, and map and slice +// elements. +func (f *Filler) MaxDepth(d int) *Filler { + f.maxDepth = d + return f +} + +// AllowUnexportedFields defines whether to fill unexported fields. +func (f *Filler) AllowUnexportedFields(flag bool) *Filler { + f.allowUnexportedFields = flag + return f +} + +// SkipFieldsWithPattern tells this Filler to skip any field whose name matches +// the supplied pattern. Call this multiple times if needed. This is useful to +// skip XXX_ fields generated by protobuf. +func (f *Filler) SkipFieldsWithPattern(pattern *regexp.Regexp) *Filler { + f.skipFieldPatterns = append(f.skipFieldPatterns, pattern) + return f +} + +// SimpleSelfFiller represents an object that knows how to randfill itself. +// +// Unlike NativeSelfFiller, this interface does not cause the type in question +// to depend on the randfill package. This is most useful for simple types. For +// more complex types, consider using NativeSelfFiller. +type SimpleSelfFiller interface { + // RandFill fills the current object with random data. + RandFill(r *rand.Rand) +} + +// NativeSelfFiller represents an object that knows how to randfill itself. +// +// Unlike SimpleSelfFiller, this interface allows for recursive filling of +// child objects with the same rules as the parent Filler. +type NativeSelfFiller interface { + // RandFill fills the current object with random data. + RandFill(c Continue) +} + +// Fill recursively fills all of obj's fields with something random. First +// this tries to find a custom fill function (see Funcs). If there is no +// custom function, this tests whether the object implements SimpleSelfFiller +// or NativeSelfFiller and if so, calls RandFill on it to fill itself. If that +// fails, this will see if there is a default fill function provided by this +// package. If all of that fails, this will generate random values for all +// primitive fields and then recurse for all non-primitives. +// +// This is safe for cyclic or tree-like structs, up to a limit. Use the +// MaxDepth method to adjust how deep you need it to recurse. +// +// obj must be a pointer. Exported (public) fields can always be set, and if +// the AllowUnexportedFields() modifier was called it can try to set unexported +// (private) fields, too. +// +// This is intended for tests, so will panic on bad input or unimplemented +// types. This method takes a lock for the whole Filler, so it is not +// reentrant. See Continue. +func (f *Filler) Fill(obj interface{}) { + f.lock.Lock() + defer f.lock.Unlock() + + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("Filler.Fill: obj must be a pointer") + } + v = v.Elem() + f.fillWithContext(v, 0) +} + +// FillNoCustom is just like Fill, except that any custom fill function for +// obj's type will not be called and obj will not be tested for +// SimpleSelfFiller or NativeSelfFiller. This applies only to obj and not other +// instances of obj's type or to obj's child fields. +// +// obj must be a pointer. Exported (public) fields can always be set, and if +// the AllowUnexportedFields() modifier was called it can try to set unexported +// (private) fields, too. +// +// This is intended for tests, so will panic on bad input or unimplemented +// types. This method takes a lock for the whole Filler, so it is not +// reentrant. See Continue. +func (f *Filler) FillNoCustom(obj interface{}) { + f.lock.Lock() + defer f.lock.Unlock() + + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("Filler.FillNoCustom: obj must be a pointer") + } + v = v.Elem() + f.fillWithContext(v, flagNoCustomFill) +} + +const ( + // Do not try to find a custom fill function. Does not apply recursively. + flagNoCustomFill uint64 = 1 << iota +) + +func (f *Filler) fillWithContext(v reflect.Value, flags uint64) { + fc := &fillerContext{filler: f} + fc.doFill(v, flags) +} + +// fillerContext carries context about a single filling run, which lets Filler +// be thread-safe. +type fillerContext struct { + filler *Filler + curDepth int +} + +func (fc *fillerContext) doFill(v reflect.Value, flags uint64) { + if fc.curDepth >= fc.filler.maxDepth { + return + } + fc.curDepth++ + defer func() { fc.curDepth-- }() + + if !v.CanSet() { + if !fc.filler.allowUnexportedFields || !v.CanAddr() { + return + } + v = reflect.NewAt(v.Type(), unsafe.Pointer(v.UnsafeAddr())).Elem() + } + + if flags&flagNoCustomFill == 0 { + // Check for both pointer and non-pointer custom functions. + if v.CanAddr() && fc.tryCustom(v.Addr()) { + return + } + if fc.tryCustom(v) { + return + } + } + + if fn, ok := fillFuncMap[v.Kind()]; ok { + fn(v, fc.filler.r) + return + } + + switch v.Kind() { + case reflect.Map: + if fc.filler.genShouldFill() { + v.Set(reflect.MakeMap(v.Type())) + n := fc.filler.genElementCount() + for i := 0; i < n; i++ { + key := reflect.New(v.Type().Key()).Elem() + fc.doFill(key, 0) + val := reflect.New(v.Type().Elem()).Elem() + fc.doFill(val, 0) + v.SetMapIndex(key, val) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Ptr: + if fc.filler.genShouldFill() { + v.Set(reflect.New(v.Type().Elem())) + fc.doFill(v.Elem(), 0) + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Slice: + if fc.filler.genShouldFill() { + n := fc.filler.genElementCount() + v.Set(reflect.MakeSlice(v.Type(), n, n)) + for i := 0; i < n; i++ { + fc.doFill(v.Index(i), 0) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Array: + if fc.filler.genShouldFill() { + n := v.Len() + for i := 0; i < n; i++ { + fc.doFill(v.Index(i), 0) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + skipField := false + fieldName := v.Type().Field(i).Name + for _, pattern := range fc.filler.skipFieldPatterns { + if pattern.MatchString(fieldName) { + skipField = true + break + } + } + if !skipField { + fc.doFill(v.Field(i), 0) + } + } + case reflect.Chan: + fallthrough + case reflect.Func: + fallthrough + case reflect.Interface: + fallthrough + default: + panic(fmt.Sprintf("can't fill type %v, kind %v", v.Type(), v.Kind())) + } +} + +// tryCustom searches for custom handlers, and returns true iff it finds a match +// and successfully randomizes v. +func (fc *fillerContext) tryCustom(v reflect.Value) bool { + // First: see if we have a fill function for it. + doCustom, ok := fc.filler.customFuncs[v.Type()] + if !ok { + // Second: see if it can fill itself. + if v.CanInterface() { + intf := v.Interface() + if fillable, ok := intf.(SimpleSelfFiller); ok { + fillable.RandFill(fc.filler.r) + return true + } + if fillable, ok := intf.(NativeSelfFiller); ok { + fillable.RandFill(Continue{fc: fc, Rand: fc.filler.r}) + return true + } + } + // Finally: see if there is a default fill function. + doCustom, ok = fc.filler.defaultFuncs[v.Type()] + if !ok { + return false + } + } + + switch v.Kind() { + case reflect.Ptr: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.New(v.Type().Elem())) + } + case reflect.Map: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.MakeMap(v.Type())) + } + default: + return false + } + + doCustom.Call([]reflect.Value{ + v, + reflect.ValueOf(Continue{ + fc: fc, + Rand: fc.filler.r, + }), + }) + return true +} + +// Continue can be passed to custom fill functions to allow them to use +// the correct source of randomness and to continue filling their members. +type Continue struct { + fc *fillerContext + + // For convenience, Continue implements rand.Rand via embedding. + // Use this for generating any randomness if you want your filling + // to be repeatable for a given seed. + *rand.Rand +} + +// Fill continues filling obj. obj must be a pointer or a reflect.Value of a +// pointer. See Filler.Fill. +func (c Continue) Fill(obj interface{}) { + v, ok := obj.(reflect.Value) + if !ok { + v = reflect.ValueOf(obj) + } + if v.Kind() != reflect.Ptr { + panic("Continue.Fill: obj must be a pointer") + } + v = v.Elem() + c.fc.doFill(v, 0) +} + +// FillNoCustom continues filling obj, except that any custom fill function for +// obj's type will not be called and obj will not be tested for +// SimpleSelfFiller or NativeSelfFiller. See Filler.FillNoCustom. +func (c Continue) FillNoCustom(obj interface{}) { + v, ok := obj.(reflect.Value) + if !ok { + v = reflect.ValueOf(obj) + } + if v.Kind() != reflect.Ptr { + panic("Continue.FillNoCustom: obj must be a pointer") + } + v = v.Elem() + c.fc.doFill(v, flagNoCustomFill) +} + +const defaultStringMaxLen = 20 + +// String makes a random string up to n characters long. If n is 0, the default +// size range is [0-20). The returned string may include a variety of (valid) +// UTF-8 encodings. +func (c Continue) String(n int) string { + return randString(c.Rand, n) +} + +// Uint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func (c Continue) Uint64() uint64 { + return randUint64(c.Rand) +} + +// Bool returns true or false randomly. +func (c Continue) Bool() bool { + return randBool(c.Rand) +} + +func fillInt(v reflect.Value, r *rand.Rand) { + v.SetInt(int64(randUint64(r))) +} + +func fillUint(v reflect.Value, r *rand.Rand) { + v.SetUint(randUint64(r)) +} + +func randfillTime(t *time.Time, c Continue) { + var sec, nsec int64 + // Allow for about 1000 years of random time values, which keeps things + // like JSON parsing reasonably happy. + sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) + // Nanosecond values greater than 1Bn are technically allowed but result in + // time.Time values with invalid timezone offsets. + nsec = c.Rand.Int63n(999999999) + *t = time.Unix(sec, nsec) +} + +var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ + reflect.Bool: func(v reflect.Value, r *rand.Rand) { + v.SetBool(randBool(r)) + }, + reflect.Int: fillInt, + reflect.Int8: fillInt, + reflect.Int16: fillInt, + reflect.Int32: fillInt, + reflect.Int64: fillInt, + reflect.Uint: fillUint, + reflect.Uint8: fillUint, + reflect.Uint16: fillUint, + reflect.Uint32: fillUint, + reflect.Uint64: fillUint, + reflect.Uintptr: fillUint, + reflect.Float32: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(float64(r.Float32())) + }, + reflect.Float64: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(r.Float64()) + }, + reflect.Complex64: func(v reflect.Value, r *rand.Rand) { + v.SetComplex(complex128(complex(r.Float32(), r.Float32()))) + }, + reflect.Complex128: func(v reflect.Value, r *rand.Rand) { + v.SetComplex(complex(r.Float64(), r.Float64())) + }, + reflect.String: func(v reflect.Value, r *rand.Rand) { + v.SetString(randString(r, 0)) + }, + reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { + panic("filling of UnsafePointers is not implemented") + }, +} + +// randBool returns true or false randomly. +func randBool(r *rand.Rand) bool { + return r.Int31()&(1<<30) == 0 +} + +type int63nPicker interface { + Int63n(int64) int64 +} + +// UnicodeRange describes a sequential range of unicode characters. +// Last must be numerically greater than First. +type UnicodeRange struct { + First, Last rune +} + +// UnicodeRanges describes an arbitrary number of sequential ranges of unicode characters. +// To be useful, each range must have at least one character (First <= Last) and +// there must be at least one range. +type UnicodeRanges []UnicodeRange + +// choose returns a random unicode character from the given range, using the +// given randomness source. +func (ur UnicodeRange) choose(r int63nPicker) rune { + count := int64(ur.Last - ur.First + 1) + return ur.First + rune(r.Int63n(count)) +} + +// CustomStringFillFunc constructs a FillFunc which produces random strings. +// Each character is selected from the range ur. If there are no characters +// in the range (cr.Last < cr.First), this will panic. +func (ur UnicodeRange) CustomStringFillFunc(n int) func(s *string, c Continue) { + ur.check() + return func(s *string, c Continue) { + *s = ur.randString(c.Rand, n) + } +} + +// check is a function that used to check whether the first of ur(UnicodeRange) +// is greater than the last one. +func (ur UnicodeRange) check() { + if ur.Last < ur.First { + panic("UnicodeRange.check: the last encoding must be greater than the first") + } +} + +// randString of UnicodeRange makes a random string up to 20 characters long. +// Each character is selected form ur(UnicodeRange). +func (ur UnicodeRange) randString(r *rand.Rand, max int) string { + if max == 0 { + max = defaultStringMaxLen + } + n := r.Intn(max) + sb := strings.Builder{} + sb.Grow(n) + for i := 0; i < n; i++ { + sb.WriteRune(ur.choose(r)) + } + return sb.String() +} + +// defaultUnicodeRanges sets a default unicode range when users do not set +// CustomStringFillFunc() but want to fill strings. +var defaultUnicodeRanges = UnicodeRanges{ + {' ', '~'}, // ASCII characters + {'\u00a0', '\u02af'}, // Multi-byte encoded characters + {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) +} + +// CustomStringFillFunc constructs a FillFunc which produces random strings. +// Each character is selected from one of the ranges of ur(UnicodeRanges). +// Each range has an equal probability of being chosen. If there are no ranges, +// or a selected range has no characters (.Last < .First), this will panic. +// Do not modify any of the ranges in ur after calling this function. +func (ur UnicodeRanges) CustomStringFillFunc(n int) func(s *string, c Continue) { + // Check unicode ranges slice is empty. + if len(ur) == 0 { + panic("UnicodeRanges is empty") + } + // if not empty, each range should be checked. + for i := range ur { + ur[i].check() + } + return func(s *string, c Continue) { + *s = ur.randString(c.Rand, n) + } +} + +// randString of UnicodeRanges makes a random string up to 20 characters long. +// Each character is selected form one of the ranges of ur(UnicodeRanges), +// and each range has an equal probability of being chosen. +func (ur UnicodeRanges) randString(r *rand.Rand, max int) string { + if max == 0 { + max = defaultStringMaxLen + } + n := r.Intn(max) + sb := strings.Builder{} + sb.Grow(n) + for i := 0; i < n; i++ { + sb.WriteRune(ur[r.Intn(len(ur))].choose(r)) + } + return sb.String() +} + +// randString makes a random string up to 20 characters long. The returned string +// may include a variety of (valid) UTF-8 encodings. +func randString(r *rand.Rand, max int) string { + return defaultUnicodeRanges.randString(r, max) +} + +// randUint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func randUint64(r *rand.Rand) uint64 { + return uint64(r.Uint32())<<32 | uint64(r.Uint32()) +}